import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class HttpClient {
private static final String endLine = "\r\n";
public static void main(String[] args) {
// 默认请求的资源
String uri = "index.html";
if (args.length != 0){
uri = args[0];
}
// 处理 get 请求
// doGet("localhost", 80, uri);
doGet("www.baidu.com", 80, "/");
}
/**
* 向指定服务器发送 get 请求
* @param host 目标服务器
* @param port 目标服务器的端口号
* @param uri 请求的资源名称
*/
public static void doGet(String host, int port, String uri){
Socket socket = null;
try {
socket =new Socket(host, port);
StringBuffer stringBuffer = new StringBuffer();
// HTTP 协议 请求行 请求方式 请求内容 HTTP协议版本号
// stringBuffer.append("GET / HTTP/1.1" + endLine);
stringBuffer.append("GET " + uri + " HTTP/1.1" + endLine);
// 请求头
// 客户端能接受的文件类型
stringBuffer.append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" + endLine);
// 客户端能接受的压缩格式
// stringBuffer.append("Accept-Encoding: gzip, deflate, br" + endLine);
// 客户端能够接受的语言
stringBuffer.append("Accept-Language: zh-CN,zh;q=0.9" + endLine);
// 客户端与服务器的连接状态
stringBuffer.append("Connection: keep-alive"+ endLine);
// 目标主机
stringBuffer.append("Host: " + host + endLine);
// 用户代理,代表用户的身份,浏览器版本号、系统架构、系统版本。
stringBuffer.append("User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36" + endLine);
// 请求头后需要以后一个空行
stringBuffer.append(endLine);
// 准备当前的输入输出流
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 向服务器发送请求内容
outputStream.write(stringBuffer.toString().getBytes());
// 程序睡眠 5s
Thread.sleep(5000);
int size = inputStream.available();
byte[] bytes = new byte[size];
int length = inputStream.read(bytes);
String text = new String(bytes, 0, length);
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
HTTP 简易浏览器
最新推荐文章于 2024-05-11 01:30:01 发布