socket编程2-httpclient

/*不能接收数据*/

package Chapter2;

import java.io.*;
import java.net.*;

public class HTTPClient {
    String host = "www.baidu.com";
    int port = 80;
    Socket socket;

    public void createSocket() throws UnknownHostException, IOException {
        socket = new Socket("www.baidu.com", 80);
        System.out.println("---已连接---");
    }

    public void communicate() throws IOException {
        System.out.println("---正在发送数据---");
        StringBuffer sb = new StringBuffer("GET "+"/more/"+" HTTP/1.1 ");
        sb.append("Host: www.baidu.com ");
        sb.append("Accept: */* ");
        sb.append("Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3 ");
        sb.append("Accept-Encoding: gzip, deflate ");
        sb.append("User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0 ");
        sb.append("Connection: keep-alive ");

            // 发出HTTP请求
            OutputStream socketOut = socket.getOutputStream();
            // 发送数据时,先把字符串形式的请求信息转换为字节数组,再发送
            socketOut.write(sb.toString().getBytes());
//            socket.shutdownOutput();// 关闭输出流
            System.out.println("---完成发送,正在接收数据---");
            // 接收响应结果
            // 接收数据时,把接收到的字节写到一个ByteArrayOutputStream中(具有可自动增长的缓冲区)
            InputStream socketIn = socket.getInputStream();
            ByteArrayOutputStream buffer = new  ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len=socketIn.read(buff))!= -1) {
            buffer.write(buff, 0, len);
            }
            System.out.println(new String(buffer.toByteArray()));
            socket.close();
            // 把字节数据转换成字符串
//            BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
//            String data;
//            while ((data=br.readLine()) != null) {
//                System.out.println(data);
//            }System.out.println("---完成接收---");

    }

    public static void main(String[] args) throws Exception {
        HTTPClient client = new HTTPClient();
        client.createSocket();
        client.communicate();
    }

}

原文地址:https://www.cnblogs.com/stay-sober/p/4158796.html