我想在我的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);
}
答案 0 :(得分:0)
首先,您忘记通过在最后添加另一条\r\n
行来正确完成请求。
其次,您正在阅读从服务器获得的所有内容,而无需确定实际响应的持续时间。
请使用HTTP库,或通过学习the HTTP specification来学习正确使用HTTP协议。
答案 1 :(得分:0)
(套接字需要一些努力;您可能更喜欢不同的方法。标准的JSE是URL.openConnection。)
指定编码,否则它是默认的enocding - 不可移植。
new InputStreamReader(socket.getInputStream(), "Windows-1252"));
反方向相同:
requestmsg.getBytes("Windows-1252")
这是Windows Latin-1,即使指定了更有限的Latin-1“ISO-8859-1”,浏览器也会接受。稍后检查编码。
发送标头最好不要说它已准备好使用压缩:
//requestmsg += "Accept-Encoding: gzip, deflate, sdch\r\n";
用空行关闭请求标头:
requestmsg += "\r\n";
BufferedOutputStream更适合DataOutputStream恕我直言。