java 实现简单的http客户端
1、废话不多说,代码如下
package com.linhuaming.test;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
/**
* http客户端 测试
*/
public class HttpClientTest {
public static void main(String[] args) throws Exception {
try{
// 请求地址、端口
String httpURL = "http://127.0.0.1:8080/demo?username=lhm&password=123456";
URL url = new URL(httpURL);
String host = url.getHost();
int port = url.getPort();
// socket客户端
Socket socket = new Socket(host,port);
// 发送请求
OutputStream outputStream = socket.getOutputStream();
String req = createRequestHeader(url);
outputStream.write(req.getBytes());
outputStream.flush();
System.out.println("------------------------请求结果-------------------------");
System.out.println(req);
Thread.sleep(2000);
// 响应结果
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
StringBuilder ret = new StringBuilder();
while ((len = inputStream.read(buffer)) >= 0) {
ret.append(new String(buffer, 0, len));
}
System.out.println("------------------------响应结果-------------------------");
System.out.println(ret);
// 关闭流
inputStream.close();
outputStream.close();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 创建请求头部
* @param url
* @return
* @throws MalformedURLException
*/
public static String createRequestHeader(URL url) throws MalformedURLException {
StringBuilder sb = new StringBuilder();
String path = "/";
if (url.getPath() != null && url.getPath().length() > 0) {
path = url.getPath();
}
String BR = "\r\n";
sb.append("GET " + path + " HTTP/1.0" + BR);
sb.append("HOST: " + url.getHost() + BR);
sb.append("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + BR);
sb.append(BR);
sb.append(url.getQuery());
return sb.toString();
}
}
2、运行结果,如下图所示
linhuaming