为什么没有成功的“带套接字的HTTP GET请求”?

时间:2015-05-04 15:42:48

标签: java android http sockets http-request

我想在我的Android应用程序中发送GET消息。之后我想收到GET响应为200 OK。但我没有完成。我收到了408 Request Time-outDate或什么都没有。你能救我吗?

String requestmsg = "GET / HTTP/1.1\r\n";
requestmsg += "Host: www.ktu.edu.tr\r\n";
requestmsg += "Connection: keep-alive\r\n";
requestmsg += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n";
requestmsg += "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW 64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36\r\n";
requestmsg += "Accept-Encoding: gzip, deflate, sdch\r\n";
requestmsg += "Accept-Language: en-US,en;q=0.8,en-GB;q=0.6\r\n";


DataOutputStream dos = null;
BufferedReader dis = null;
try {

    Log.d("ClientActivity", "Connecting...");
    String addr = InetAddress.getByName("www.ktu.edu.tr").getHostAddress().toString();
    Socket socket = new Socket(addr, 80);
    String data = "";

    try {
        Log.d("ClientActivity", "C: Sending command.");

        dos = new DataOutputStream(socket.getOutputStream());
        dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        dos.write(requestmsg.getBytes());
        Log.i("ClientActivity", "RequestMsg Sent");

        StringBuilder sb = new StringBuilder();

        while ((data = dis.readLine()) != null) {
            sb.append(data);
        }
        Log.i("ClientActivity", "C: Sent.");
        Log.i("ClientActivity", "C: Received " + sb.toString());
    } catch (Exception e) {
        Log.e("ClientActivity", "S: Error", e);

    }

    socket.close();
    Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
    Log.e("ClientActivity", "C: Error", e);
}

1 个答案:

答案 0 :(得分:0)

  • 您错过了Content-Length标题
  • 您在请求标题的末尾错过了一个空行
  • 您没有根据内容长度或分块正确阅读回复。

简而言之,不要自己实施HTTP。使用URLHttpURLConnection。它会处理所有这些细节以及更多细节。