[Calling Third-party API - Apache HttpClient] HttpClient Tutorial
HttpClient is a HTTP/1.1 compliant HTTP agent implementation based on HttpCore. It also provides reusable components for client-side authentication, HTTP state management, and HTTP connection management...
Posted by Mr.Vincent on
2020-11-18
Estimated Reading Time 14 Minutes
Words 2.7k In Total
Viewed Times
Apache HttpClient 简介
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。
// HTTP GET Example HttpGethttpGet=newHttpGet("http://targethost/homepage"); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try (CloseableHttpResponseresponse1= httpclient.execute(httpGet)) { System.out.println(response1.getStatusLine()); HttpEntityentity1= response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); }
// HTTP POST Example HttpPosthttpPost=newHttpPost("http://targethost/login"); List<NameValuePair> nvps= Lists.newArrayList(); nvps.add(newBasicNameValuePair("username", "vip")); nvps.add(newBasicNameValuePair("password", "secret")); httpPost.setEntity(newUrlEncodedFormEntity(nvps));
try (CloseableHttpResponseresponse2= httpclient.execute(httpPost)) { System.out.println(response2.getStatusLine()); HttpEntityentity2= response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } }
@Test voidfluentApiTest()throws IOException { // The fluent API relieves the user from having to deal with manual deallocation of system // resources at the cost of having to buffer response content in memory in some cases. Request.Get("http://targethost/homepage") .execute() .returnContent();
@Test voidhttpclientGetTest()throws IOException { /* * https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY,访问后的 json 数据格式如下: * { * "date": "2020-11-17", * "explanation": "What's creating these long glowing streaks in the sky? No one is sure. Known as Strong Thermal Emission Velocity Enhancements (STEVEs), these luminous light-purple sky ribbons may resemble regular auroras, but recent research reveals significant differences. A STEVE's great length and unusual colors, when measured precisely, indicate that it may be related to a subauroral ion drift (SAID), a supersonic river of hot atmospheric ions thought previously to be invisible. Some STEVEs are now also thought to be accompanied by green picket fence structures, a series of sky slats that can appear outside of the main auroral oval that does not involve much glowing nitrogen. The featured wide-angle composite image shows a STEVE in a dark sky above Childs Lake, Manitoba, Canada in 2017, crossing in front of the central band of our Milky Way Galaxy.", * "hdurl": "https://apod.nasa.gov/apod/image/2011/SteveMilkyWay_NasaTrinder_6144.jpg", * "media_type": "image", * "service_version": "v1", * "title": "A Glowing STEVE and the Milky Way", * "url": "https://apod.nasa.gov/apod/image/2011/SteveMilkyWay_NasaTrinder_960.jpg" * } */ ObjectMappermapper=newObjectMapper(); try (CloseableHttpClientclient= HttpClients.createDefault()) { HttpGetrequest=newHttpGet("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"); APODresponse= client.execute(request, httpResponse -> mapper.readValue(httpResponse.getEntity().getContent(), APOD.class)); System.out.println(response.title);// A Glowing STEVE and the Milky Way } }
//普通写法 CloseableHttpClienthttpClient= HttpClients.createDefault(); HttpPosthttpPost=newHttpPost(uri); //伪装浏览器请求 httpPost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !