私のアプリでは、あらゆる種類のPOST
リクエストをサーバーに送信する必要があります。これらのリクエストには、応答があるものとないものがあります。
これは、リクエストの送信に使用しているコードです。
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
メッセージを送信し、リクエストの送信直後に接続を切断できるようにする方法です。これは、応答がないためです。