如何从Android应用程序发送HTTP请求到Heroku
我有一个使用twilio sdk并由heroku服务器托管的android应用程序。我试图在我的应用程序中推送一个按钮,向heroku发送一个HTTP请求,向Twilio发送一个REST API请求来更新我的twiml URL。目前我试图发送HTTP请求的方式不起作用。我浏览了所有可以找到的示例,但没有一个展示如何执行此功能。有人知道怎么做这个吗?提前致谢。如何从Android应用程序发送HTTP请求到Heroku
这是我尝试发送HTTP请求的Heroku
holdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yourappnamehere.herokuapp.com/hello");
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//setting a toast to see if this is being initiated
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
这是我更新的代码包括凌空库
holdButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//setting up a request queue from Volley API
//RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
String url = "http://yourappnamehere.herokuapp.com/hello";
// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
我会建议使用像谷歌凌空库代码非常光滑 https://developer.android.com/training/volley/index.html
HttpRequest已从API级别22弃用。最好避免使用usi那个。改为使用java.net.HttpUrlConnection。
但是,如果您仍想使用它,上面的代码需要在上面注释中提到的UI线程之外的线程上运行。
我已经安装了适用于android的Volley库,当我按下按钮时,什么也没有发生。对于HTTP请求和RESTful API,我是新手。我如何更新我的参数让Twilio知道我想立即使用该URL?这是格式正确吗?我想要做的就是发送一个URL到Twilio来更新我的twiml。我更新了我的代码。 –
你有没有把这个添加到你的Manifest文件中?
是的,我已经在清单文件中有。 –
首先使用'AsyncTask'来进行所有的网络调用,因为如果你不这样做,它会给你一个异常'NetworkOnMainThreadException'。其次,使用'HttpURLConnection'类在任何URL /服务器上进行GET/POST调用。它更容易,更简单,不推荐使用'DefaultHttpClient'。 [这是Java中的基本示例](http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/) –