Java http request client example -
i new in computer networking , have exercise 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 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 run program, run long time, , found readutf() method. run 20s display message:
does request "get / http/1.1 host:gg.gg " not correct, or error here? want use instruction form, not solution. thanks! (i'm not @ english much)
- an http 'end of line marker' cr lf or
\r\n
. - the 'simple request' format
simple-request = "get" sp request-uri crlf
you should do:
string httprequest = "get /\r\n";
in addition, in.readutf()
uses 'modified utf-8' , not want, expects size of string specified first 2 bytes.
while not efficient, works:
int read; while ((read = in.read()) != -1) { system.out.print((char) read); }
(this ignores encoding response is, happens come utf-8 , that's fine casting (char)
. proper encoding handling out of scope answer.)
Comments
Post a Comment