[英]How to send HTTP request from android app to Heroku
我有一个使用twilio sdk并由heroku服务器托管的android应用。 我试图按我的应用程序中的按钮以将HTTP请求发送到heroku,以将REST API请求发送到Twilio以更新我的twiml URL。 我尝试发送HTTP请求的当前方法不起作用。 我浏览了所有可以找到的示例,但没有一个示例说明如何执行此功能。 有人知道怎么做这个吗? 提前致谢。
这是我尝试将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();
}
;
});
我建议使用像Google Volley这样的库,它非常漂亮https://developer.android.com/training/volley/index.html
从API级别22开始不推荐使用HttpRequest。最好的做法是避免使用它。 请改用java.net.HttpUrlConnection。
但是,如果仍要使用它,则上面的代码需要在上面注释中提到的UI线程之外的其他线程上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.