我有一個使用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();
}
;
});
首先使用'AsyncTask'來進行所有的網絡調用,因爲如果你不這樣做,它會給你一個異常'NetworkOnMainThreadException'。其次,使用'HttpURLConnection'類在任何URL /服務器上進行GET/POST調用。它更容易,更簡單,不推薦使用'DefaultHttpClient'。 [這是Java中的基本示例](http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/) –