HttpClient入门实例

it2024-01-14  65

HttpClient简单介绍 `HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。 特性

基于标准、纯净的Java语言。实现了Http1.0和Http1.1

以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

支持HTTPS协议。

通过Http代理建立透明的连接。

利用CONNECT方法通过Http代理建立隧道的https连接。

Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

插件式的自定义认证方案。

便携可靠的套接字工厂使它更容易的使用第三方解决方案。

连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

自动处理Set-Cookie中的Cookie。

插件式的自定义Cookie策略。

Request的输出流可以避免流中内容直接缓冲到socket服务器。

Response的输入流可以有效的从socket服务器直接读取相应内容。

在http1.0和http1.1中利用KeepAlive保持持久连接。

直接获取服务器发送的response code和 headers。

设置连接超时的能力。

实验性的支持http1.1 response caching。

源代码基于Apache License 可免费获取。

实例 使用前先导入pom.xml依赖

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency>

使用方法 使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

创建HttpClient对象。创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。释放连接。无论执行方法是否成功,都必须释放连接 创建HttpClient对象。 package com.by.controller; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; //@Component 把该工具类交给spring容器管理 相当于ioc @Component public class HttpClient { //有参 public String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } //无参 只需要传一个url路径就可以 public String doGet(String url) { return doGet(url, null); } //有参 public String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8"); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public String doPost(String url) { return doPost(url, null); } public String doJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { //释放资源 response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } }

2.测试通道是否连接

//@RunWith(SpringJUnit4ClassRunner.class) 测试使用的注解 //@ContextConfiguration(value = "classpath:spring.xml") 获取到spring容器中的bean // @Autowired Di依赖注入 把工具类注入进来 //下面方法测试工具类中的 GET POST 方法 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "classpath:spring.xml") public class HttpTest { @Autowired private HttpClient httpClient; //传无参 @Test public void test1(){ String get = httpClient.doGet("http://localhost:8080/test1.do"); System.out.println(get); } //传有参 @Test public void test2(){ Map<String, String> map = new HashMap<>(); map.put("test1","测试post有参方法参数1..."); map.put("test2","测试post有参方法参数2..."); String get = httpClient.doGet("http://localhost:8080/test2.do",map); System.out.println(get); } //传无参 @Test public void test3(){ //这个tomcat在浏览器解析不了post方法 String post = httpClient.doPost("http://localhost:8080/test3.do"); System.out.println(post); } //传有参 @Test public void test4(){ Map<String, String> map = new HashMap<>(); map.put("test1","测试post有参方法参数1..."); map.put("test2","测试post有参方法参数2..."); //这个tomcat在浏览器解析不了post方法 String post = httpClient.doPost("http://localhost:8080/test4.do",map); System.out.println(post); } //实现自定义接口 返回json格式 @Test public void test5(){ String s = httpClient.doGet("http://localhost:8080/test5.do"); System.out.println(s); } }

3.另一个项目访问 这里需要注意以下,浏览器只支持Get方法 测试post方法,使用postman软件 里面提供了这些方法

/* * 相当于 * @Controller @ResponseBody 通过ResponseBody可以返回回来数据 * */ @RestController public class HttpController { //被传 测试get无参方法 @GetMapping("test1") public String test1(){ System.out.println("test1执行....."); return "success"; } //被传 测试get有参方法 @GetMapping("test2") public String test2(String test1 , String test2){ System.out.println(test1+"-------"+test2); System.out.println("test2执行....."); return "success"; } //被传 测试post无参方法 @PostMapping("test3") public String test3(){ System.out.println("test3..被执行"); return "success"; } //被传 测试post有参方法 @PostMapping("test4") public String test4(String test1 , String test2){ System.out.println(test1+"____________"+test2); System.out.println("test4..被执行"); return "success"; } //自定义一个接口,json格式 @GetMapping("test5") public Map<Object, Object> test5(){ Map<Object, Object> map = new HashMap<>(); map.put("name","八一IT"); map.put("major","java"); map.put("state","在校状态.."); System.out.println(map); return map; } }

测试完成! 学生有不对的地方可以指点,一起学习 奥力给!!!!!!!!!

最新回复(0)