使用套接字从HTTP Post接收数据

时间:2012-10-24 09:57:47

标签: java android http sockets

我的要求是在android中使用Socket接收HTTP Post请求(内容是JSON文件)。当我打印socket.getInputStream()时,我得到:

POST/HTTP/1.1
Content length:41
Content-type: application/json
Host:10.0.2.15:5001
Connection: Keep Alive
User-Agent: Apache HTTPClient/Unavailable(Java 1.4)

CRLF(Carriage return line feed)-  

Actual Contents of JSON<Data>

我使用链接https://forums.oracle.com/forums/thread.jspa?messageID=7076709,但它只打印“Content-type:application / json Logcat中的主机:10.0“(可能长度为41)。

我的代码是:

    serverSocket = new ServerSocket(portNumber);
    while(true){ 
    socket = serverSocket.accept();
    List<String> headers = new ArrayList<String>();
    String str;
    BufferedReader reader = new BufferedReader(new  InputStreamReader(socket.getInputStream()));
    while ((str = reader.readLine()) != null)
    {
    headers.add(str);
    if (str.startsWith("Content-Length: "))
    {
    break; // and don't get the next line!
    }
    }
    int contentLength = Integer.parseInt(headers.get(headers.size() - 1).substring("Content-Length: ".length()));

   for(int j=0;j<headers.size();j++)
   {
    Log.d("Headers:",headers.get(j));
    }
    StringBuilder requestContent = new StringBuilder();
    int ch;
    for (int i = 0; i < contentLength; i++)
    {
    requestContent.append((char) reader.read());
    }
    Log.d("The request content is: ",""+requestContent);

这是我的输出: 头:  POST / HTTP / 1.1  内容长度:41

requestContent:  Content-Type:application / json  主持人:10。

有人可以指导我如何做到这一点吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

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以获取更多参考资料