日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

发送http和https请求工具类 Json封装数据

發布時間:2024/9/27 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 发送http和https请求工具类 Json封装数据 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在一些業務中我們可要調其他的接口(第三方的接口) 這樣就用到我接下來用到的工具類。
用這個類需要引一下jar包的坐標

<dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.3</version></dependency>

引好坐標后就可以使用這個工具類了;

Connection.Response post = HttpUtils.post("http://localhost:10090/Controller/httpToJson",str); String body = post.body(); System.out.println("響應報文:"+body);

str代表你需要傳的參數 一般是json類型的數據

訪問成功后一般會返回你一個json的數據,但是這個數據有一些問題,它會進行轉譯。我把這個字符串進行了一些處理。

{"result":"{\"FoodID\":\"A66J54DW9IKJ75U3\",\"FoodName\":\"桃子\",\"FoodBrand\":\"龍冠\",\"FoodPlace\":\"吉林\",\"FoodText\":\"四打擊我家的娃哦哦囧\",\"FoodImg\":\"sdasdasdasd\",\"FoodProInfo\":[{\"ProjectName\":\"澆水\",\"UserName\":\"周銳\",\"OperationDescribe\":\"給桃子樹澆水茁壯成長\",\"ImgUrl\":\"asdlpalplpd23\",\"OperationTm\":\"20200616103856\"}],\"FoodPackInfo\":null,\"FoodDetectionInfo\":null,\"FoodLogInfo\":null}","code":0,"message":"查詢智能合約成功"}

對這個串進行替換等一些操作,然后把它轉成json對象。通過json工具類把它自動封裝到實體類型中,
(在進行封裝實體的時候一定要注意,json串的屬性和實體的屬性要完全相同)否則會報錯的(避免入坑)

Connection.Response post = HttpUtils.post("http://localhost:10090/fabricController/queryChaincode",str);String body = post.body();String replace = body.replace("\\\"", "\"");String replace1 = replace.replace(":\"{", ":{");String replace2 = replace1.replace("}\",", "},");String replace3 = replace2.replace("{\"result\":", "");String replace4 = replace3.replace(",\"code\":0,\"message\":\"查詢智能合約成功\"}", ""); com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(replace4);FoodAllInfo foodAllInfo = JSON.parseObject(replace4, FoodAllInfo.class); package com.gblfy.order.utils;import org.jsoup.Connection; import org.jsoup.Connection.Response; import org.jsoup.Jsoup;import javax.net.ssl.*; import java.io.*; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set;public class HttpUtils {/*** 請求超時時間*/private static final int TIME_OUT = 120000;/*** Https請求*/private static final String HTTPS = "https";/*** 發送Get請求** @param url 請求URL* @return 服務器響應對象* @throws IOException*/public static Response get(String url) throws IOException {return get(url, null);}/*** 發送Get請求** @param url 請求URL* @param headers 請求頭參數* @return 服務器響應對象* @throws IOException*/public static Response get(String url, Map<String, String> headers) throws IOException {if (null == url || url.isEmpty()) {throw new RuntimeException("The request URL is blank.");}// 如果是Https請求if (url.startsWith(HTTPS)) {getTrust();}Connection connection = Jsoup.connect(url);connection.method(Connection.Method.GET);connection.timeout(TIME_OUT);connection.ignoreHttpErrors(true);connection.ignoreContentType(true);if (null != headers) {connection.headers(headers);}Response response = connection.execute();return response;}/*** 發送JSON格式參數POST請求** @param url 請求路徑* @param params JSON格式請求參數* @return 服務器響應對象* @throws IOException*/public static Response post(String url, String params) throws IOException {return doPostRequest(url, null, null, null, params);}/*** 發送JSON格式參數POST請求** @param url 請求路徑* @param headers 請求頭中設置的參數* @param params JSON格式請求參數* @return 服務器響應對象* @throws IOException*/public static Response post(String url, Map<String, String> headers, Map<String, String> params,String flag) throws IOException {return doPostRequest(url,headers,params,null,null);}/*** 字符串參數post請求** @param url 請求URL地址* @param paramMap 請求字符串參數集合* @return 服務器響應對象* @throws IOException*/public static Response post(String url, Map<String, String> headers) throws IOException {return doPostRequest(url, headers, null, null, null);}/*** 帶上傳文件的post請求** @param url 請求URL地址* @param paramMap 請求字符串參數集合* @param fileMap 請求文件參數集合* @return 服務器響應對象* @throws IOException*/public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap)throws IOException {return doPostRequest(url, null, paramMap, fileMap, null);}/*** 執行post請求** @param url 請求URL地址* @param paramMap 請求字符串參數集合* @param fileMap 請求文件參數集合* @return 服務器響應對象* @throws IOException*/private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap,Map<String, File> fileMap, String jsonParams) throws IOException {if (null == url || url.isEmpty()) {throw new RuntimeException("The request URL is blank.");}// 如果是Https請求if (url.startsWith(HTTPS)) {getTrust();}Connection connection = Jsoup.connect(url);connection.method(Connection.Method.POST);connection.timeout(TIME_OUT);connection.ignoreHttpErrors(true);connection.ignoreContentType(true);if (null != headers) {connection.headers(headers);}// 收集上傳文件輸入流,最終全部關閉List<InputStream> inputStreamList = null;try {// 添加文件參數if (null != fileMap && !fileMap.isEmpty()) {inputStreamList = new ArrayList<InputStream>();InputStream in = null;File file = null;Set<Entry<String, File>> set = fileMap.entrySet();for (Entry<String, File> e : set) {file = e.getValue();in = new FileInputStream(file);inputStreamList.add(in);connection.data(e.getKey(), file.getName(), in);}}// 設置請求體為JSON格式內容else if (null != jsonParams && !jsonParams.isEmpty()) {connection.header("Content-Type", "application/json;charset=UTF-8");connection.requestBody(jsonParams);}// 普通表單提交方式else {connection.header("Content-Type", "application/x-www-form-urlencoded");}// 添加字符串類參數if (null != paramMap && !paramMap.isEmpty()) {connection.data(paramMap);}Response response = connection.execute();return response;} catch (FileNotFoundException e) {throw e;} catch (IOException e) {throw e;}// 關閉上傳文件的輸入流finally {if (null != inputStreamList) {for (InputStream in : inputStreamList) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}}}/*** 獲取服務器信任*/private static void getTrust() {try {HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});SSLContext context = SSLContext.getInstance("TLS");context.init(null, new X509TrustManager[] { new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}} }, new SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());} catch (Exception e) {e.printStackTrace();}} }

總結

以上是生活随笔為你收集整理的发送http和https请求工具类 Json封装数据的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。