HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用
本文實(shí)例為大家分享了HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用的具體代碼,供大家參考,具體內(nèi)容如下
依賴(lài):
<dependency> ? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId> ? ? ? ? ? ? <artifactId>httpclient</artifactId> ? ? ? ? ? ? <version>4.5.6</version> ? ? ? ? </dependency> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>com.alibaba</groupId> ? ? ? ? ? ? <artifactId>fastjson</artifactId> ? ? ? ? ? ? <version>1.2.58</version> ? ? ? ? </dependency> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId> ? ? ? ? ? ? <artifactId>httpmime</artifactId> ? ? ? ? ? ? <version>4.5.5</version> </dependency>
服務(wù)提供者:
/**
? ? * get請(qǐng)求
*/
? ? @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請(qǐng)求
*/
@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);
? ? }封裝的工具類(lèi):
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請(qǐng)求
? ? ? ? Map<String, Object> mapget = new ConcurrentHashMap<>();
? ? ? ? mapget.put("id", 1);
? ? ? ? AjaxResult<Uesr> 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請(qǐng)求
? ? ? ? Map<String, Object> mappost = new ConcurrentHashMap<>();
? ? ? ? mappost.put("id", 2);
? ? ? ? mappost.put("name", "陳虎001post");
? ? ? ? Uesr uesr1 = new Uesr();
? ? ? ? uesr1.setName("chenpost");
? ? ? ? uesr1.setId(001);
? ? ? ? AjaxResult<Integer> 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);
? ? ? ? //文件請(qǐng)求
? ? ? ? List<File> files = new ArrayList<>();
? ? ? ? File file = new File("D:/t.txt");
? ? ? ? files.add(file);
? ? ? ? Map<String, String> mapfile = new ConcurrentHashMap<>();
? ? ? ? mappost.put("id", " 2");
? ? ? ? mappost.put("fileMd5", "陳虎001file");
? ? ? ? AjaxResult<Integer> resultFile = httpClientHelper.updataFile("http://127.0.0.1:8081/test14", "multipartFile", files, mapfile, Integer.class);
? ? ? ? final Integer ntegerfile = resultFile.getData();
? ? ? ? System.err.println(ntegerfile);
? ? }
? ? /**
? ? ?* 帶參數(shù)的get請(qǐng)求
? ? ?*
? ? ?* @param url ? ? ? ? ?請(qǐng)求地址
? ? ?* @param parameValues 參數(shù)
? ? ?* @param headerValues ? ?請(qǐng)求頭參數(shù)
? ? ?* @param clazz ? ? ? ? ?返回參數(shù)類(lèi)型
? ? ?* @return
? ? ?* @throws Exception
? ? ?*/
? ? public <T> AjaxResult doGet(String url, Map<String, Object> parameValues, Map<String, String> headerValues, Class<T> clazz) throws Exception {
? ? ? ? // 聲明URIBuilder
? ? ? ? URIBuilder uriBuilder = new URIBuilder(url);
? ? ? ? // 判斷參數(shù)map是否為非空
? ? ? ? if (parameValues != null) {
? ? ? ? ? ? // 遍歷參數(shù)
? ? ? ? ? ? for (Map.Entry<String, Object> entry : parameValues.entrySet()) {
? ? ? ? ? ? ? ? // 設(shè)置參數(shù)
? ? ? ? ? ? ? ? uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // 2 創(chuàng)建httpGet對(duì)象,相當(dāng)于設(shè)置url請(qǐng)求地址
? ? ? ? HttpGet httpGet = new HttpGet(uriBuilder.build());
? ? ? ? /*
? ? ? ? ?* 添加請(qǐng)求頭信息
? ? ? ? ?*/
? ? ? ? //判斷請(qǐng)求頭是否不為空
? ? ? ? if (headerValues != null) {
? ? ? ? ? ? for (Map.Entry<String, String> entry : headerValues.entrySet()) {
? ? ? ? ? ? ? ? httpGet.addHeader(entry.getKey(), entry.getValue());
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // 傳輸?shù)念?lèi)型
? ? ? ? httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
? ? ? ? // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車(chē),發(fā)起請(qǐng)求
? ? ? ? CloseableHttpResponse response = httpClient.execute(httpGet);
? ? ? ? // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
? ? ? ? return pasResponse(response, clazz);
? ? }
? ? /**
? ? ?* 帶參數(shù)的post請(qǐng)求
? ? ?*
? ? ?* @param url ? ? ? 請(qǐng)求地址
? ? ?* @param parameter 參數(shù)
? ? ?* @param headerValues 請(qǐng)求頭參數(shù)
? ? ?* @param clazz ? ? ? 返回參數(shù)類(lèi)型
? ? ?* @return
? ? ?* @throws Exception
? ? ?*/
? ? public <T> AjaxResult doPost(String url, Object parameter, Map<String, String> headerValues, Class<T> clazz) throws Exception {
? ? ? ? // 聲明httpPost請(qǐng)求
? ? ? ? HttpPost httpPost = new HttpPost(url);
? ? ? ? setParam(httpPost, parameter, headerValues);
? ? ? ? // 傳輸?shù)念?lèi)型
? ? ? ? httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
? ? ? ? // 使用HttpClient發(fā)起請(qǐng)求,返回response
? ? ? ? CloseableHttpResponse response = httpClient.execute(httpPost);
? ? ? ? // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
? ? ? ? return pasResponse(response, clazz);
? ? }
? ? /**
? ? ?* 帶參數(shù)的Put請(qǐng)求
? ? ?*
? ? ?* @param url ? ? ? 請(qǐng)求地址
? ? ?* @param parameter 參數(shù)
? ? ?* @param headerValues 請(qǐng)求頭參數(shù)
? ? ?* @param clazz ? ? ? 返回參數(shù)類(lèi)型
? ? ?* @return
? ? ?* @throws Exception
? ? ?*/
? ? public <T> AjaxResult doPut(String url, Object parameter, Map<String, String> headerValues, Class<T> clazz) throws Exception {
? ? ? ? // 聲明httpPost請(qǐng)求
? ? ? ? HttpPut httpPut = new HttpPut(url);
? ? ? ? setParam(httpPut, parameter, headerValues);
? ? ? ? // 傳輸?shù)念?lèi)型
? ? ? ? httpPut.addHeader("Content-Type", "application/json; charset=UTF-8");
? ? ? ? // 使用HttpClient發(fā)起請(qǐng)求,返回response
? ? ? ? CloseableHttpResponse response = httpClient.execute(httpPut);
? ? ? ? // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
? ? ? ? return pasResponse(response, clazz);
? ? }
? ? /**
? ? ?* 遠(yuǎn)程調(diào)用傳輸文件
? ? ?*
? ? ?* @param url ? ? ? ? ?請(qǐng)求地址
? ? ?* @param fileKey ? ? ?后端接收的文件參數(shù)的名稱(chēng)
? ? ?* @param files ? ? ? ?文件集合
? ? ?* @param parameValues 其他參數(shù)
? ? ?* @param clazz 返回參數(shù)類(lèi)型
? ? ?*/
? ? public <T> AjaxResult updataFile(String url, String fileKey, List<File> files, Map<String, String> parameValues, Class<T> clazz) throws IOException {
? ? ? ? CloseableHttpClient httpClient = HttpClientBuilder.create().build();
? ? ? ? HttpPost httpPost = new HttpPost(url);
? ? ? ? CloseableHttpResponse response = null;
? ? ? ? MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
? ? ? ? //設(shè)置文件參數(shù)
? ? ? ? for (File file : files) {
? ? ? ? ? ? multipartEntityBuilder.addBinaryBody(fileKey, file, ContentType.DEFAULT_BINARY, URLEncoder.encode(file.getName(), "utf-8"));
? ? ? ? }
? ? ? ? //設(shè)置其他參數(shù)
? ? ? ? if (parameValues != null) {
? ? ? ? ? ? // 其它參數(shù)(注:自定義contentType,設(shè)置UTF-8是為了防止服務(wù)端拿到的參數(shù)出現(xiàn)亂碼)
? ? ? ? ? ? ContentType contentType = ContentType.create("application/json", Charset.forName("UTF-8"));
? ? ? ? ? ? for (Map.Entry<String, String> entry : parameValues.entrySet()) {
? ? ? ? ? ? ? ? multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(), contentType);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? HttpEntity httpEntity = multipartEntityBuilder.build();
? ? ? ? httpPost.setEntity(httpEntity);
? ? ? ? response = httpClient.execute(httpPost);
? ? ? ? // 4 解析結(jié)果,封裝返回對(duì)象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果
? ? ? ? return pasResponse(response, clazz);
? ? }
? ? /**
? ? ?* 設(shè)置參數(shù)
? ? ?*
? ? ?* @param parameter 請(qǐng)求參數(shù)
? ? ?* @param headerValues 請(qǐng)求頭參數(shù)
? ? ?*/
? ? private void setParam(HttpEntityEnclosingRequestBase requestBase, Object
? ? ? ? ? ? parameter, Map<String, String> headerValues) {
? ? ? ? // 判斷參數(shù)是否不為空
? ? ? ? if (parameter != null) {
? ? ? ? ? ? // 在傳送復(fù)雜嵌套對(duì)象時(shí),一定要把對(duì)象轉(zhuǎn)成json字符串,我這里實(shí)用的是alibaba.fastjson,當(dāng)然你也可以使用其他的json工具
? ? ? ? ? ? StringEntity requestEntity = new StringEntity(JSON.toJSONString(parameter), "utf-8");
? ? ? ? ? ? requestEntity.setContentEncoding("UTF-8");
? ? ? ? ? ? requestBase.setEntity(requestEntity);
? ? ? ? }
? ? ? ? //判斷請(qǐng)求頭是否不為空
? ? ? ? if (headerValues != null) {
? ? ? ? ? ? for (Map.Entry<String, String> entry : headerValues.entrySet()) {
? ? ? ? ? ? ? ? requestBase.addHeader(entry.getKey(), entry.getValue());
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? /**
? ? ?* 封裝返回結(jié)果
? ? ?*
? ? ?* @param response 數(shù)據(jù)集
? ? ?* @param clazz ? ? ?參數(shù)類(lèi)型
? ? ?* @param <T>
? ? ?* @return
? ? ?* @throws IOException
? ? ?*/
? ? private <T> AjaxResult pasResponse(CloseableHttpResponse response, Class<T> clazz) throws IOException {
? ? ? ? AjaxResult<T> ajaxResult = null;
? ? ? ? try {
? ? ? ? ? ? // 解析數(shù)據(jù)封裝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("返回結(jié)果轉(zhuǎn)換失敗" + e);
? ? ? ? } finally {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? // 釋放資源
? ? ? ? ? ? ? ? if (response != null) {
? ? ? ? ? ? ? ? ? ? response.close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? System.err.println("資源釋放失敗" + e);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return ajaxResult;
? ? }
}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- springBoot使用openfeign來(lái)遠(yuǎn)程調(diào)用的實(shí)現(xiàn)
- 在SpringBoot中,如何使用Netty實(shí)現(xiàn)遠(yuǎn)程調(diào)用方法總結(jié)
- SpringBoot整合Dubbo框架,實(shí)現(xiàn)RPC服務(wù)遠(yuǎn)程調(diào)用
- SpringBoot使用Netty實(shí)現(xiàn)遠(yuǎn)程調(diào)用的示例
- SpringBoot2.0 整合 Dubbo框架實(shí)現(xiàn)RPC服務(wù)遠(yuǎn)程調(diào)用方法
- SpringBoot?Http遠(yuǎn)程調(diào)用的方法
相關(guān)文章
Java8新特性之深入解析日期和時(shí)間_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Java8新特性之深入解析日期和時(shí)間_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理,需要的朋友可以參考下2017-06-06
詳解堆排序算法原理及Java版的代碼實(shí)現(xiàn)
如果將堆理解為二叉樹(shù),那么樹(shù)中任一非葉結(jié)點(diǎn)的關(guān)鍵字均不大于(或不小于)其左右孩子(若存在)結(jié)點(diǎn)的關(guān)鍵字,堆排序的時(shí)間復(fù)雜度為O(N*logN),這里我們就來(lái)詳解堆排序算法原理及Java版的代碼實(shí)現(xiàn)2016-06-06
Springboot編寫(xiě)CRUD時(shí)訪問(wèn)對(duì)應(yīng)數(shù)據(jù)函數(shù)返回null的問(wèn)題及解決方法
我在學(xué)習(xí)springboot,其中在編寫(xiě)CRUD時(shí)發(fā)現(xiàn)訪問(wèn)數(shù)據(jù)的函數(shù)執(zhí)行下去返回值是null但是其它部分正常,這篇文章主要介紹了Springboot在編寫(xiě)CRUD時(shí),訪問(wèn)對(duì)應(yīng)數(shù)據(jù)函數(shù)返回null,需要的朋友可以參考下2024-02-02
關(guān)于JAVA_HOME路徑修改之后JDK的版本依然不更改的解決辦法
今天小編就為大家分享一篇關(guān)于JAVA_HOME路徑修改之后JDK的版本依然不更改的解決辦法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-04-04
CodeGPT + IDEA + DeepSeek如何在IDEA中引入DeepS
文章介紹了如何在IDEA中使用CodeGPT和DeepSeek插件實(shí)現(xiàn)AI智能開(kāi)發(fā),具體內(nèi)容包括安裝步驟、配置APIkey和參數(shù)設(shè)置等,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-02-02

