你也许经常使用到HttpClient,但你试过使用Socket来自己模拟一个HTTP请求吗?
其实很简单,只要使用Socket向指定的Http Server端发送一个遵循http 协议的格式的一段字符串,Http Server就能正确的解析字符串,然后处理后再响应给你的客户端。
假设我们现在需要向 localhost:12345/definition这个api下发送一个请求,并传递参数name=importsource。
那么我们只需要拼接如下一段字符串通过Socket发送到Http Server就可以了(在最短的情况下):
GET /definition?name=importsource HTTP/1.1 Host: 127.0.0.1:12345 Accept: text/html Connection: Close
第一行:首先是一个http method ,然后是url ,然后是http协议。
第二行:是ip加端口组成一个host。
第三行:是内容类型。
第四行:表示完成后就关闭本次Connection。如果你不加这一行,那么连接是不会关闭的。
接下来的事情就是Socket方面的编程了。
开始吧:
public class HttpClient {
public static void main(String[] args) {
try {
StringBuffer get = new StringBuffer(200);
get.append("GET /definition?name=importsource HTTP/1.1\r\n");
get.append("Host: 127.0.0.1:12345\r\n");
get.append("Accept: text/html\r\n");
get.append("Connection: Close\r\n");
get.append("\r\n");
get.append("");
System.out.println(get);
// socket客户端连接本机的tomcat服务器,端口为8080
Socket socket = new Socket("127.0.0.1", 12345);
socket.setSoTimeout(30000);
// socket客户端发送登录请求
PrintWriter outWriter = new PrintWriter(socket.getOutputStream());
// 发送post请求
outWriter.println(get);
outWriter.flush();
// socket客户端接收tomcat返回的数据
BufferedReader inReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 以下是服务器返回的数据
System.out.println("**************** Server responsed ****************");
String tmp = "";
while ((tmp = inReader.readLine()) != null) {
// 解析服务器返回的数据,做相应的处理
System.out.println(tmp);
}
outWriter.close();
inReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
http server :
建一个spring boot rest 。
@SpringBootApplication
@RestController
public class SocketHttpApplication {
@GetMapping("/definition")
public String definition(@RequestParam("name") String name){
return name;
}
public static void main(String[] args) {
SpringApplication.run(SocketHttpApplication.class, args);
}
}
maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
执行结果:
GET /definition?name=importsource HTTP/1.1
Host: 127.0.0.1:12345
Accept: text/html
Connection: Close
******* Server responsed *******
HTTP/1.1 200
Content-Type: text/html;charset=UTF-8
Content-Length: 12
Date: Sat, 24 Jun 2017 15:36:14 GMT
Connection: close
importsource