0

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

4

1 に答える 1

0

ただ、ConnectionTimeOutHttpClientオブジェクトで設定します(コードはあなたの場合は理解するためのものであり、異なる場合があります)

int TIMEOUT_MILLISEC = 30000;  
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/json");

これで、定義したTimeoOutの後に接続が終了します。ただし、これがスローされることを確認してください。HttpRequestTimeOutExceptionでこの例外を処理する必要があります。(Try -catchを使用)

編集:または、 HttpRequestExecutorクラスを使用できます。

パッケージorg.apache.http.protocolのクラスHttpRequestExecutorから

protected boolean canResponseHaveBody (HttpRequest request, HttpResponse response)

応答にエンティティが含まれるかどうかを決定します。このクラスの実装はRFC2616に基づいています。不明なメソッドと応答コードは、エンティティによる応答を示すことになっています。派生エグゼキュータは、このメソッドをオーバーライドして、RFC2616で指定されていないメソッドと応答コードを処理できます。

于 2012-06-21T06:06:38.003 に答える