發送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() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] { new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章