本文实例为大家分享了HttpClient实现远程调用的具体代码,供大家参考,具体内容如下
依赖:
org.apache.httpcomponents httpclient 4.5.6 com.alibaba fastjson 1.2.58 org.apache.httpcomponents httpmime 4.5.5
服务提供者:
/** * get请求 */ @GetMapping("/gte3") public AjaxResult getGuke3(Integer id) throws Exception { System.err.println("id:" + id); Uesr uesr = new Uesr(); uesr.setId(11); uesr.setName("chen"); return AjaxResult.success(uesr); } /** *post请求 */ @PostMapping("/test001") public AjaxResult post1(@RequestBody Uesr uesr) { System.err.println(uesr.getId() + uesr.getName()); return AjaxResult.success(1); } /** * 文件上传 */ @PostMapping("/test14") public AjaxResult test14(MultipartFile multipartFile, String id, String fileMd5) throws IOException { System.err.println(id); System.err.println(fileMd5); final InputStream inputStream = multipartFile.getInputStream(); int i = 0; while ((i = inputStream.read()) != -1) { char c = (char) i; System.err.println(c); } return AjaxResult.success(1); }
封装的工具类:
package cn.sotos; import cn.sotos.util.AjaxResult; import cn.sotos.util.Uesr; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.ParseException; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @program: exportool * @description: * @author: hu.chen **/ public class HttpClientHelper { private static CloseableHttpClient httpClient = HttpClientBuilder.create().build(); public static void main(String[] args) throws Exception { HttpClientHelper httpClientHelper = new HttpClientHelper(); //get请求 Mapmapget = new ConcurrentHashMap<>(); mapget.put("id", 1); AjaxResult resultGet = httpClientHelper.doGet("http://127.0.0.1:8081/gte3", mapget, null, Uesr.class); System.err.println(resultGet.getCode()); System.err.println(resultGet.getMsg()); final Uesr uesr = resultGet.getData(); System.err.println(uesr.getName()); //post请求 Map mappost = new ConcurrentHashMap<>(); mappost.put("id", 2); mappost.put("name", "陈虎001post"); Uesr uesr1 = new Uesr(); uesr1.setName("chenpost"); uesr1.setId(001); AjaxResult resultPost = httpClientHelper.doPost("http://127.0.0.1:8081/test001", uesr1, null, Integer.class); System.err.println(resultPost.getCode()); System.err.println(resultPost.getMsg()); final Integer nteger = resultPost.getData(); System.err.println(nteger); //文件请求 List files = new ArrayList<>(); File file = new File("D:/t.txt"); files.add(file); Map mapfile = new ConcurrentHashMap<>(); mappost.put("id", " 2"); mappost.put("fileMd5", "陈虎001file"); AjaxResult resultFile = httpClientHelper.updataFile("http://127.0.0.1:8081/test14", "multipartFile", files, mapfile, Integer.class); final Integer ntegerfile = resultFile.getData(); System.err.println(ntegerfile); } /** * 带参数的get请求 * * @param url 请求地址 * @param parameValues 参数 * @param headerValues 请求头参数 * @param clazz 返回参数类型 * @return * @throws Exception */ public AjaxResult doGet(String url, Map parameValues, Map headerValues, Class clazz) throws Exception { // 声明URIBuilder URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空 if (parameValues != null) { // 遍历参数 for (Map.Entry entry : parameValues.entrySet()) { // 设置参数 uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); } } // 2 创建httpGet对象,相当于设置url请求地址 HttpGet httpGet = new HttpGet(uriBuilder.build()); /* * 添加请求头信息 */ //判断请求头是否不为空 if (headerValues != null) { for (Map.Entry entry : headerValues.entrySet()) { httpGet.addHeader(entry.getKey(), entry.getValue()); } } // 传输的类型 httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 return pasResponse(response, clazz); } /** * 带参数的post请求 * * @param url 请求地址 * @param parameter 参数 * @param headerValues 请求头参数 * @param clazz 返回参数类型 * @return * @throws Exception */ public AjaxResult doPost(String url, Object parameter, Map headerValues, Class clazz) throws Exception { // 声明httpPost请求 HttpPost httpPost = new HttpPost(url); setParam(httpPost, parameter, headerValues); // 传输的类型 httpPost.addHeader("Content-Type", "application/json; charset=UTF-8"); // 使用HttpClient发起请求,返回response CloseableHttpResponse response = httpClient.execute(httpPost); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 return pasResponse(response, clazz); } /** * 带参数的Put请求 * * @param url 请求地址 * @param parameter 参数 * @param headerValues 请求头参数 * @param clazz 返回参数类型 * @return * @throws Exception */ public AjaxResult doPut(String url, Object parameter, Map headerValues, Class clazz) throws Exception { // 声明httpPost请求 HttpPut httpPut = new HttpPut(url); setParam(httpPut, parameter, headerValues); // 传输的类型 httpPut.addHeader("Content-Type", "application/json; charset=UTF-8"); // 使用HttpClient发起请求,返回response CloseableHttpResponse response = httpClient.execute(httpPut); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 return pasResponse(response, clazz); } /** * 远程调用传输文件 * * @param url 请求地址 * @param fileKey 后端接收的文件参数的名称 * @param files 文件集合 * @param parameValues 其他参数 * @param clazz 返回参数类型 */ public AjaxResult updataFile(String url, String fileKey, List files, Map parameValues, Class clazz) throws IOException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = null; MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); //设置文件参数 for (File file : files) { multipartEntityBuilder.addBinaryBody(fileKey, file, ContentType.DEFAULT_BINARY, URLEncoder.encode(file.getName(), "utf-8")); } //设置其他参数 if (parameValues != null) { // 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码) ContentType contentType = ContentType.create("application/json", Charset.forName("UTF-8")); for (Map.Entry entry : parameValues.entrySet()) { multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(), contentType); } } HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); response = httpClient.execute(httpPost); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果 return pasResponse(response, clazz); } /** * 设置参数 * * @param parameter 请求参数 * @param headerValues 请求头参数 */ private void setParam(HttpEntityEnclosingRequestBase requestBase, Object parameter, Map headerValues) { // 判断参数是否不为空 if (parameter != null) { // 在传送复杂嵌套对象时,一定要把对象转成json字符串,我这里实用的是alibaba.fastjson,当然你也可以使用其他的json工具 StringEntity requestEntity = new StringEntity(JSON.toJSONString(parameter), "utf-8"); requestEntity.setContentEncoding("UTF-8"); requestBase.setEntity(requestEntity); } //判断请求头是否不为空 if (headerValues != null) { for (Map.Entry entry : headerValues.entrySet()) { requestBase.addHeader(entry.getKey(), entry.getValue()); } } } /** * 封装返回结果 * * @param response 数据集 * @param clazz 参数类型 * @param * @return * @throws IOException */ private AjaxResult pasResponse(CloseableHttpResponse response, Class clazz) throws IOException { AjaxResult ajaxResult = null; try { // 解析数据封装HttpResult if (response.getEntity() != null) { ajaxResult = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"), AjaxResult.class); ajaxResult.setData(JSONObject.parseObject(JSONObject.toJSONString(ajaxResult.getData()), clazz)); } else { ajaxResult = new AjaxResult(); } } catch (ParseException | IOException e) { System.err.println("返回结果转换失败" + e); } finally { try { // 释放资源 if (response != null) { response.close(); } } catch (IOException e) { System.err.println("资源释放失败" + e); } } return ajaxResult; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。