Socket sends HTTP protocol

Source: Internet
Author: User

I. SendingGetRequest

import java.net.*;import java.io.*;public class URLSender {    /**     * @param args */ public static void main(String[] args) throws IOException {        try {            Socket socket = new Socket("www.nwu.edu.cn", 80);            boolean autoflush = true;           PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));            //send an HTTP request to the web server           out.println("GET / HTTP/1.1");            out.println("Host: nwu.edu.cn");            out.println("Connection: Close");            out.println();            //read the response                   boolean loop = true;           StringBuffer sb = new StringBuffer(8096);            while (loop) {               if (in.ready()) {                int i = 0;                while (i != -1) {                    i = in.read();                    sb.append((char) i);                }                loop = false;             }            //Thread.currentThread().sleep(50);            }            //display the response to the out console            System.out.println(sb.toString());          socket.close();       } catch (UnknownHostException e) {            System.err.println("Don't know about host: Victest.");             System.exit(1);        } catch (IOException e) {            System.err.println("Couldn't get I/O for " + "the connection to: Victest.");             System.exit(1);        }   }}

2. UseSocketSend a POST request

Try {
// Construct data
String data = urlencoder. encode ("key1", "UTF-8") + "=" + urlencoder. encode ("value1", "UTF-8 ");
Data + = "&" + urlencoder. encode ("key2", "UTF-8") + "=" + urlencoder. encode ("value2", "UTF-8 ");

// CreateSocketToHost
String hostname = "hostname.com ";
Int Port = 80;
Inetaddress ADDR = inetaddress. getbyname (hostname );
Socket Socket= NewSocket(ADDR, Port );

// Send Header
String Path = "/servlet/someservlet ";
Bufferedwriter wR = new bufferedwriter (New outputstreamwriter (Socket. Getoutputstream (), "utf8 "));
Wr. Write ("Post" + path +"HTTP/1.0/R/N ");
Wr. Write ("Content-Length:" + data. Length () + "/R/N ");
Wr. Write ("Content-Type: Application/X-WWW-form-urlencoded/R/N ");
Wr. Write ("/R/N ");

// Send data
Wr. Write (data );
Wr. Flush ();

//GetResponse
Bufferedreader RD = new bufferedreader (New inputstreamreader (Socket. Getinputstream ()));
String line;
While (line = RD. Readline ())! = NULL ){
// Process line...
}
Wr. Close ();
Rd. Close ();
} Catch (exception e ){
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.