HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用
更新時(shí)間:2022年08月14日 09:20:54 作者:陳虎_63
這篇文章主要為大家詳細(xì)介紹了HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用的具體代碼,供大家參考,具體內(nè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請求 */ ? ? @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請求 ? ? ? ? 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請求 ? ? ? ? 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); ? ? ? ? //文件請求 ? ? ? ? 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請求 ? ? ?* ? ? ?* @param url ? ? ? ? ?請求地址 ? ? ?* @param parameValues 參數(shù) ? ? ?* @param headerValues ? ?請求頭參數(shù) ? ? ?* @param clazz ? ? ? ? ?返回參數(shù)類型 ? ? ?* @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對象,相當(dāng)于設(shè)置url請求地址 ? ? ? ? HttpGet httpGet = new HttpGet(uriBuilder.build()); ? ? ? ? /* ? ? ? ? ?* 添加請求頭信息 ? ? ? ? ?*/ ? ? ? ? //判斷請求頭是否不為空 ? ? ? ? if (headerValues != null) { ? ? ? ? ? ? for (Map.Entry<String, String> entry : headerValues.entrySet()) { ? ? ? ? ? ? ? ? httpGet.addHeader(entry.getKey(), entry.getValue()); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? // 傳輸?shù)念愋? ? ? ? ? httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded"); ? ? ? ? // 3 使用HttpClient執(zhí)行httpGet,相當(dāng)于按回車,發(fā)起請求 ? ? ? ? CloseableHttpResponse response = httpClient.execute(httpGet); ? ? ? ? // 4 解析結(jié)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 帶參數(shù)的post請求 ? ? ?* ? ? ?* @param url ? ? ? 請求地址 ? ? ?* @param parameter 參數(shù) ? ? ?* @param headerValues 請求頭參數(shù) ? ? ?* @param clazz ? ? ? 返回參數(shù)類型 ? ? ?* @return ? ? ?* @throws Exception ? ? ?*/ ? ? public <T> AjaxResult doPost(String url, Object parameter, Map<String, String> headerValues, Class<T> clazz) throws Exception { ? ? ? ? // 聲明httpPost請求 ? ? ? ? HttpPost httpPost = new HttpPost(url); ? ? ? ? setParam(httpPost, parameter, headerValues); ? ? ? ? // 傳輸?shù)念愋? ? ? ? ? httpPost.addHeader("Content-Type", "application/json; charset=UTF-8"); ? ? ? ? // 使用HttpClient發(fā)起請求,返回response ? ? ? ? CloseableHttpResponse response = httpClient.execute(httpPost); ? ? ? ? // 4 解析結(jié)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 帶參數(shù)的Put請求 ? ? ?* ? ? ?* @param url ? ? ? 請求地址 ? ? ?* @param parameter 參數(shù) ? ? ?* @param headerValues 請求頭參數(shù) ? ? ?* @param clazz ? ? ? 返回參數(shù)類型 ? ? ?* @return ? ? ?* @throws Exception ? ? ?*/ ? ? public <T> AjaxResult doPut(String url, Object parameter, Map<String, String> headerValues, Class<T> clazz) throws Exception { ? ? ? ? // 聲明httpPost請求 ? ? ? ? HttpPut httpPut = new HttpPut(url); ? ? ? ? setParam(httpPut, parameter, headerValues); ? ? ? ? // 傳輸?shù)念愋? ? ? ? ? httpPut.addHeader("Content-Type", "application/json; charset=UTF-8"); ? ? ? ? // 使用HttpClient發(fā)起請求,返回response ? ? ? ? CloseableHttpResponse response = httpClient.execute(httpPut); ? ? ? ? // 4 解析結(jié)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 遠(yuǎn)程調(diào)用傳輸文件 ? ? ?* ? ? ?* @param url ? ? ? ? ?請求地址 ? ? ?* @param fileKey ? ? ?后端接收的文件參數(shù)的名稱 ? ? ?* @param files ? ? ? ?文件集合 ? ? ?* @param parameValues 其他參數(shù) ? ? ?* @param clazz 返回參數(shù)類型 ? ? ?*/ ? ? 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é)果,封裝返回對象httpResult,相當(dāng)于顯示相應(yīng)的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 設(shè)置參數(shù) ? ? ?* ? ? ?* @param parameter 請求參數(shù) ? ? ?* @param headerValues 請求頭參數(shù) ? ? ?*/ ? ? private void setParam(HttpEntityEnclosingRequestBase requestBase, Object ? ? ? ? ? ? parameter, Map<String, String> headerValues) { ? ? ? ? // 判斷參數(shù)是否不為空 ? ? ? ? if (parameter != null) { ? ? ? ? ? ? // 在傳送復(fù)雜嵌套對象時(shí),一定要把對象轉(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); ? ? ? ? } ? ? ? ? //判斷請求頭是否不為空 ? ? ? ? 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ù)類型 ? ? ?* @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; ? ? } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- springBoot使用openfeign來遠(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)文章
關(guān)于MyBatis plus條件構(gòu)造器的逐條詳解
什么是條件構(gòu)造器呢?簡單來說,條件構(gòu)造器就是用來生成我們查數(shù)據(jù)庫的sql。它可以簡化sql代碼的編寫,靈活、方便且易于維護(hù)2021-09-09SpringBoot實(shí)現(xiàn)獲取客戶端IP地理位置
在當(dāng)今互聯(lián)的世界中,了解客戶端的地理位置對于提供個(gè)性化服務(wù)和增強(qiáng)用戶體驗(yàn)至關(guān)重要,使用本文為大家介紹了SpringBoot獲取客戶端IP地理位置的相關(guān)方法,需要的小伙伴可以參考下2023-11-11spring中BeanUtils.copyProperties的使用(深拷貝,淺拷貝)
本文主要介紹了spring中BeanUtils.copyProperties的使用(深拷貝,淺拷貝),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05如何利用java控制鼠標(biāo)操作一些重復(fù)的事情
這篇文章主要給大家介紹了關(guān)于如何利用java控制鼠標(biāo)操作一些重復(fù)的事情,主要利用的是Robot類,Robot可以模擬鼠標(biāo)和鍵盤的輸入,相當(dāng)于Java版的按鍵精靈,需要的朋友可以參考下2021-12-12