Use the Java NIO to construct the HTTP request body and get the response content.
Package Com.test.nio;import Java.net.inetsocketaddress;import Java.nio.bytebuffer;import Java.nio.channels.socketchannel;import Java.nio.charset.charset;public class Testsocketforbaidu {/** * @param args * @ Throws Exception */private static Charset Charset = Charset.forname ("UTF8");//create GBK Character set public static void main ( String[] args) throws Exception {Socketchannel Channel=socketchannel.open (new inetsocketaddress ("www.itbuluoge.com", )); String line= "get/http/1.1 \ r \ n"; line+= "host:www.itbuluoge.com\r\n"; line+= "\ r \ n"; Channel.write (Charset.encode ( line)); Bytebuffer buffer = bytebuffer.allocate (1024);//create 1024-byte buffered int size=channel.read (buffer), while (Size!=-1) { Buffer.flip (); while (Buffer.hasremaining ()) {System.out.print (Charset.decode (buffer));} Buffer.clear (); size=channel.read (buffer);}}}
Output results
We can see, can return to the homepage of the website, and can parse the body, here to notice, when constructing the HTTP request, the minimum required protocol or parameters are:
get/http/1.1
Host:www.itbuluoge.com
Note that the end must be two "\r\n\r\n".
Java constructs HTTP requests using NIO