在我的應用程序中,我需要發送各種POST
請求到服務器。其中一些請求有答覆,其他請求沒有答覆。Android:發送沒有迴應的帖子
這是我用來發送請求的代碼:
private static final String TAG = "Server";
private static final String PATH = "http://10.0.0.2:8001/data_connection";
private static HttpResponse response = null;
private static StringEntity se = null;
private static HttpClient client;
private static HttpPost post = null;
public static String actionKey = null;
public static JSONObject sendRequest(JSONObject req) {
try {
client = new DefaultHttpClient();
actionKey = req.getString("actionKey");
se = new StringEntity(req.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "application/json"));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post = new HttpPost(PATH);
post.setEntity(se);
Log.d(TAG, "http request is being sent");
response = client.execute(post);
Log.d(TAG, "http request was sent");
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertFromInputStream(in);
in.close();
return new JSONObject(a);
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "encoding request to String entity faild!");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (JSONException e) {
Log.d(TAG, "no ActionKey");
e.printStackTrace();
}
return null;
}
private static String convertFromInputStream(InputStream in)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return (sb.toString());
}
這是發送請求的
AsyncTask
類的代碼:
class ServerRequest extends AsyncTask<JSONObject, Void, JSONObject> {
@Override
protected JSONObject doInBackground(JSONObject... params) {
JSONObject req = params[0];
JSONObject response = Server.sendRequest(req);
return response;
}
@Override
protected void onPostExecute(JSONObject result) {
// HANDLE RESULT
super.onPostExecute(result);
}
}
我的問題當服務器沒有返回響應時開始。即使完成工作,
AsyncTask
線程仍保持打開狀態,因爲
HTTPClient
從不關閉連接。
有沒有辦法不等待迴應?這肯定會給服務器增加很多開銷,因爲所有試圖連接到它的Android應用程序都會使連接保持活動狀態,並且可能會導致應用程序本身出現很多問題。
基本上,我正在尋找的是一種方法,將允許我發送到POST
消息並在請求發送後立即終止連接,因爲沒有響應以我的方式發送。
這並沒有什麼意義。爲什麼沒有迴應?除非你長時間輪詢,否則應該有一些迴應,即使它沒有一個機構,只是一個狀態碼。如果你沒有得到/等待迴應,你怎麼能確定服務器甚至收到你的請求? –