查看“HttpClient 工具类”的源代码
←
HttpClient 工具类
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
https://www.bilibili.com/video/BV1AN411Z7mx?p=12 === pom.xml === <syntaxhighlight lang="xml"> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> </syntaxhighlight> === HttpClientUtil.java === <syntaxhighlight lang="java"> import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; 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 java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { public static 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; } } public static String doGet(String url) { return doGet(url, null); } public static 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<>(); 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 static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建 Httpclient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; //执行 http 请求 try { //创建 Http Post 请求 HttpPost httpPost = new HttpPost(url); //创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } } </syntaxhighlight> === JsonUtils.java === <syntaxhighlight lang="java"> import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import java.util.Map; public class JsonUtils { private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 将对象转换成 JSON 字符串 * @param data * @return */ public static String objectToJson(Object data) { String string = null; try { string = MAPPER.writeValueAsString(data); } catch (JsonProcessingException e) { e.printStackTrace(); } return string; } /** * 将 json 结果集转化为对象 * @param jsonData json 数据 * @param beanType 对象中的 object 类型 * @return * @param <T> */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { T t = null; try { t = MAPPER.readValue(jsonData, beanType); } catch (JsonProcessingException e) { e.printStackTrace(); } return t; } /** * 将 json 数据转换成 pojo 对象 list * @param jsonData * @param beanType * @return * @param <T> */ public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); List<T> list = null; try { list = MAPPER.readValue(jsonData, javaType); } catch (Exception e) { e.printStackTrace(); } return list; } /** * 把 json 转换为 Map 工具方法 * @param jsonData * @param keyType * @param valueType * @return * @param <K> * @param <V> */ public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) { JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType); Map<K, V> map = null; try { map = MAPPER.readValue(jsonData, javaType); } catch (JsonProcessingException e) { e.printStackTrace(); } return map; } } </syntaxhighlight> === ClientApplicationTests.java === <syntaxhighlight lang="java"> import io.github.jihch.pojo.People; import io.github.jihch.utils.HttpClientUtil; import org.junit.jupiter.api.Test; import org.junit.runners.Parameterized; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest public class ClientApplicationTests { @Test void httpClientGet() { String result = HttpClientUtil.doGet("http://localhost:8080/demo"); System.out.println(result); result = HttpClientUtil.doGet("http://localhost:8080/demo5"); System.out.println(result); ObjectMapper objectMapper = new ObjectMapper(); People people = null; try { people = objectMapper.readValue(result, People.class); System.out.println(people); } catch (JsonProcessingException e) { e.printStackTrace(); } result = HttpClientUtil.doGet("http://localhost:8080/demo2?name=jihch&age=15"); System.out.println(result); result = HttpClientUtil.doGet("http://localhost:8080/demo6"); System.out.println(result); List<People> list = JsonUtils.jsonToList(result, People.class); System.out.println(list); for (People p : list) { System.out.println(p); } Map<String, String> map = new HashMap<>(); map.put("name", "jihch"); map.put("age", "15"); result = HttpClientUtil.doGet("http://localhost:8080/demo2", map); System.out.println(result); } } </syntaxhighlight><syntaxhighlight lang="console"> demo {"id":1,"name":"jihch"} People{id=1, name='jihch'} name:jihch,age:15 [{"id":1,"name":"jihch1"},{"id":2,"name":"jihch2"}] [People{id=1, name='jihch1'}, People{id=2, name='jihch2'}] People{id=1, name='jihch1'} People{id=2, name='jihch2'} name:jihch,age:15 </syntaxhighlight>
返回至
HttpClient 工具类
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息