Java调用Http/Https接口(4)--HttpClient调用Http/Https接口

HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。

1、服务端

参见Java调用Http接口(1)--编写服务端 

2、调用Http接口 2.1、GET请求

public static void get() { String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet get = new HttpGet(requestPath); CloseableHttpResponse response = httpClient.execute(get); System.out.println("GET返回状态:" + response.getStatusLine()); HttpEntity responseEntity = response.getEntity(); System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity)); //流畅api调用 String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8")); System.out.println("GET fluent返回结果:" + result); } catch (Exception e) { e.printStackTrace(); } finally { close(httpClient); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwdzxy.html