【问题标题】:Receiving data from HTTP Post using Sockets使用套接字从 HTTP Post 接收数据
【发布时间】:2012-10-24 09:57:47
【问题描述】:

我的要求是在 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 中的 Host: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);

这是我的输出: 标题: 发布/HTTP/1.1 内容长度:41

请求内容: 内容类型:应用程序/json 主持人:10。

有人可以指导我如何完成吗?提前致谢!

【问题讨论】:

  • 我已经编辑了@Waqas 的问题
  • 你为什么使用套接字而不是 http 库?
  • 请让我知道这种情况是否可行(因为我的要求是这样实现)。我还需要一些关于使用哪个 HTTP 库的指导?会不会很轻? @artbristol
  • @user1741274 看看这个问题的答案stackoverflow.com/questions/6329468/create-http-server-android
  • @Arvin 我提供的链接中似乎有一些(我从未亲自使用过)

标签: java android http sockets


【解决方案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 更多参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多