原来都是浏览器发送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;
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);
User user = MAPPER.readValue(response, User.class); System.out.println(user);
String value = MAPPER.writeValueAsString(user); System.out.println(value); } }
|
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 {
@Autowired private RestTemplate restTemplate;
@Test public void httpGet() { User user = this.restTemplate.getForObject("http://localhost:8888/user/1", User.class); System.out.println(user); } }
|