SOCKET發送HTTP協議

來源:互聯網
上載者:User

一、發送Get請求

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、用Socket發送一個POST請求

    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");
    
        // Create a socket to the host
        String hostname = "hostname.com";
        int port = 80;
        InetAddress addr = InetAddress.getByName(hostname);
        Socket socket = new Socket(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();
    
        // Get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            // Process line...
        }
        wr.close();
        rd.close();
    } catch (Exception e) {
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.