处理Android中的POST请求

时间:2011-11-23 17:38:57

标签: android http post

我正在尝试使用DefaultHttpServerConnection在Android中实现一个处理POST请求的简单HTTP服务器,但我的问题在于接收封闭的实体。

DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader(); 

String method = request.getRequestLine().getMethod().toUpperCase();
if (method.equals("POST")) {
    if (DEBUG) Log.d(TAG, "POST received");
    handleUpload(conn, request);
}

还有handleUpload方法:

private void handleUpload(DefaultHttpServerConnection conn, HttpRequest request) throws HttpException, IOException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1,1), 200, "OK");       
    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(request.getRequestLine());
    conn.receiveRequestEntity(enclosingRequest);
    if (DEBUG) Log.d(TAG, "Before input");
    String r = EntityUtils.toString(enclosingRequest.getEntity());
    if (DEBUG) Log.d(TAG, "Entity: " + r);

    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
}

EntityUtils.toString()中的执行块。使用的客户端代码:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("STH", "do sth!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

对于noob问题抱歉。

1 个答案:

答案 0 :(得分:1)

DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));

http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf