简体   繁体   中英

Java http request client example

I am new in computer networking and I have a exercise about create java http client example.

The exercise instruction:

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();

and this is my code:

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();
    }
}

but when I run the program, it run very long time, and I found that is the readUTF() method. It run about 20s then display this message: 调试细节

Does my request "GET / HTTP/1.1 Host:gg.gg " not correct, or any another error here? I want to use the instruction form, not another solution. Thanks! (I'm not good at English very much)

  • An HTTP 'end of line marker' is CR LF or \\r\\n .
  • The 'simple request' format is Simple-Request = "GET" SP Request-URI CRLF

You should do:

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

In addition, in.readUTF() uses 'modified UTF-8' and is not what you want, as it expects the size of the string to be specified as the first 2 bytes.

While not efficient , this works:

int read;

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

(This ignores the encoding that the response actually is, but it happens to come back as UTF-8 and that's perfectly fine for casting with (char) . Proper encoding handling is out of scope for this answer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM