HttpClient實現(xiàn)遠程調(diào)用
更新時間:2022年08月14日 09:20:54 作者:陳虎_63
這篇文章主要為大家詳細介紹了HttpClient實現(xiàn)遠程調(diào)用的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了HttpClient實現(xià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>
服務提供者:
/** ? ? * 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ù) ? ? ? ? ? ? ? ? uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? // 2 創(chuàng)建httpGet對象,相當于設置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,相當于按回車,發(fā)起請求 ? ? ? ? CloseableHttpResponse response = httpClient.execute(httpGet); ? ? ? ? // 4 解析結(jié)果,封裝返回對象httpResult,相當于顯示相應的結(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,相當于顯示相應的結(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,相當于顯示相應的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 遠程調(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ù) ? ? ? ? for (File file : files) { ? ? ? ? ? ? multipartEntityBuilder.addBinaryBody(fileKey, file, ContentType.DEFAULT_BINARY, URLEncoder.encode(file.getName(), "utf-8")); ? ? ? ? } ? ? ? ? //設置其他參數(shù) ? ? ? ? if (parameValues != null) { ? ? ? ? ? ? // 其它參數(shù)(注:自定義contentType,設置UTF-8是為了防止服務端拿到的參數(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,相當于顯示相應的結(jié)果 ? ? ? ? return pasResponse(response, clazz); ? ? } ? ? /** ? ? ?* 設置參數(shù) ? ? ?* ? ? ?* @param parameter 請求參數(shù) ? ? ?* @param headerValues 請求頭參數(shù) ? ? ?*/ ? ? private void setParam(HttpEntityEnclosingRequestBase requestBase, Object ? ? ? ? ? ? parameter, Map<String, String> headerValues) { ? ? ? ? // 判斷參數(shù)是否不為空 ? ? ? ? if (parameter != null) { ? ? ? ? ? ? // 在傳送復雜嵌套對象時,一定要把對象轉(zhuǎn)成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<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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
spring中BeanUtils.copyProperties的使用(深拷貝,淺拷貝)
本文主要介紹了spring中BeanUtils.copyProperties的使用(深拷貝,淺拷貝),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05