Android:发送没有回复的帖子

时间:2012-06-21 05:58:23

标签: java android http-post apache-httpclient-4.x

在我的应用中,我需要向服务器发送各种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消息并在发送请求后立即终止连接,因为没有响应。

1 个答案:

答案 0 :(得分:0)

只需使用HttpClient对象设置ConnectionTimeOut(代码是为了您的理解,可能会有所不同)

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 之后终止连接。但请确保这将抛出TimeOutException,因此您必须在 HttpRequest 中处理此异常..(使用Try -catch)

编辑或者您可以使用 HttpRequestExecutor 类。

来自包HttpRequestExecutor

的课程org.apache.http.protocol
protected boolean canResponseHaveBody (HttpRequest request, HttpResponse response)

决定实体是否附带回复。此类中的实现基于RFC 2616.未知方法和响应代码应表示对实体的响应。 派生执行程序可以重写此方法以处理RFC 2616中未指定的方法和响应代码。