java主动发送http请求

java主动发送http请求

原来都是浏览器发送http请求,java接收。java这边也是可以主动发送http请求的。有三种方式

  • HttpClient
  • OKHttp
  • RestTemplate

1. HttpClient

这是apache的一个库,先导入

1
2
3
4
5
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>

看看这个工具类,直接复制过去用就行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class HttpTests {

CloseableHttpClient httpClient;

//通过jackson处理json数据
private static final ObjectMapper MAPPER = new ObjectMapper();

@Before
public void init() {
httpClient = HttpClients.createDefault();
}

@Test
public void testGet() throws IOException {
HttpGet request = new HttpGet("http://www.baidu.com");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
}

@Test
public void testPost() throws IOException {
HttpPost request = new HttpPost("https://www.oschina.net/");
request.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
}

@Test
public void testGetPojo() throws IOException {
HttpGet request = new HttpGet("http://localhost:8888/user/1");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response); //response是json字符串

User user = MAPPER.readValue(response, User.class);
System.out.println(user); //user是对象

String value = MAPPER.writeValueAsString(user);
System.out.println(value); //又变回json字符串
}
}

2. RestTemplate

这是spring自带的,在spring-web包中

写在了test包下,所以有了两个注解,也是一样,直接复制用即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpDemoApplication.class)
public class HttpDemoApplicationTests {

//除了httpClient,spring官方也提供了一个RestTemplate用于发送http请求
//还包括了像jackson一样处理json字符串序列化和反序列化的功能
//要通过有@Congratulation的java类注入,这个测试用例在HttpDemoApplication引导类中由@Bean注入,可以过去看看
@Autowired
private RestTemplate restTemplate;

@Test
public void httpGet() {
User user = this.restTemplate.getForObject("http://localhost:8888/user/1", User.class);
System.out.println(user);
}
}
#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×