Java http请求客户端示例

时间:2014-03-06 09:13:21

标签: java http request client

我是计算机网络的新手,我有一个关于创建java http客户端示例的练习。

运动指导:

Socket soc = new Socket(host, port);

DataInputStream in = new DataInputStream(soc.getInputStream());
BufferedWriter out= new BufferedWriter(new 
OutputStreamWriter(soc.getOutputStream())); 

out.write(httpRequest);
out.flush();

String httpResponse= in.readUTF();

这是我的代码:

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class MyTest{
    public static void main(String[] args) throws UnknownHostException, IOException{

        String host = "gg.gg";
        String httpRequest = "GET / HTTP/1.1 Host:gg.gg ";
        int port = 80;

        Socket soc = new Socket(host, port);


        DataInputStream in = new DataInputStream(soc.getInputStream());
        BufferedWriter out= new BufferedWriter(new 
        OutputStreamWriter(soc.getOutputStream())); 


        out.write(httpRequest);
        out.flush();


        String httpResponse = in.readUTF();

        System.out.println(httpResponse);
        //soc.close();
    }
}

但是当我运行程序时,它会运行很长时间,我发现这是readUTF()方法。 它运行大约20秒然后显示此消息: Debug detail

我的请求“GET / HTTP / 1.1 Host:gg.gg”不正确,还是其他任何错误? 我想使用指令表,而不是另一种解决方案。谢谢! (我不太擅长英语)

1 个答案:

答案 0 :(得分:0)

  • HTTP'行结束标记'是CR LF或\r\n
  • “简单请求”格式为Simple-Request = "GET" SP Request-URI CRLF

你应该这样做:

String httpRequest = "GET /\r\n";

此外,in.readUTF()使用'修改过的UTF-8'并不是您想要的,因为它希望将字符串的大小指定为前2个字节。

虽然不是效率,但这可行:

int read;

while ((read = in.read()) != -1)
{
  System.out.print((char) read);
}

(这忽略了响应实际上的编码,但它恰好以UTF-8的形式返回,并且对于使用(char)进行转换非常好。正确的编码处理超出了这个答案的范围。)< / p>