欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中的原生post請求方式

 更新時間:2023年10月07日 08:38:02   作者:沙皮狗你不懂  
這篇文章主要介紹了Java中的原生post請求方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1.post請求方式(有參數(shù))

因為請求地址為https 需要配置不驗證證書

/**
     * post請求方式(有參數(shù)) 因為請求地址為https 需要配置不驗證證書
     */
    public static String post(String strUrl, Map<String, Object> params) {
        try {
            // 添加信任主機
            trustAllHosts();
            // 創(chuàng)建連接
            URL url = new URL(strUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            // 不驗證配置
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            // 設置請求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("accept","*/*");
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 設置發(fā)送數(shù)據(jù)的格式json
            connection.setRequestProperty("Content-Type","application/json");
            // 設置token appkey
            connection.setRequestProperty("apikey","Z31jdnojkYFg3z3mXourHjP5gmpg9Ms9");
            // 設置接收數(shù)據(jù)的格式json
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            // 阿里巴巴的fastjson
            out.append(JSON.toJSONString(params));
            out.flush();
            out.close();
            // 請求成功
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                // 讀取響應
                StringBuffer respResult = new StringBuffer();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    respResult.append(line);
                }
                reader.close();
                log.info("Req Success{}" + respResult.toString());
                return respResult.toString();
            }
        } catch (Exception e) {
            log.info("Req Error{}" + e.getMessage());
            return e.getMessage();
        }
        // 請求失敗
        return null;
    }
/**
     * 不驗證配置
     */
    private final static HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;
    /**
     * 添加信任主機
     */
    private static void trustAllHosts() {
        // 創(chuàng)建不驗證證書鏈的信任管理器 這里使用的是x509證書 此處的MyX509TrustManager()為實現(xiàn)重寫方法
        TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {}
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {}
        }};
        // 安裝所有信任的信任管理器
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            //HttpsURLConnection通過SSLSocket來建立與HTTPS的安全連接,SSLSocket對象是由SSLSocketFactory生成的。
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.post請求方式(無參數(shù))

/**
     * post請求方式(無參數(shù))
     */
    public static String post(String strUrl) {
        try {
            // 創(chuàng)建連接
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 設置請求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "keep-alive");
            // 設置接收數(shù)據(jù)的格式json
            connection.setRequestProperty("Accept", "application/json");
            // connection.setRequestProperty("Content-Type", "application/json"); // 設置發(fā)送數(shù)據(jù)的格式json
            connection.connect();
            // 獲取響應碼
            int code = connection.getResponseCode();
            // 請求成功
            if (code == 200) {
                // 讀取響應
                StringBuffer respResult = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    respResult.append(line);
                }
                reader.close();
                log.info("Req Success{}" + respResult.toString());
                return respResult.toString();
            }
        } catch (Exception e) {
            log.info("Req Error{}" + e.getMessage());
            return e.getMessage();
        }
        // 請求失敗
        return null;
    }
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
 * 重寫的X509TrustManager類
 */
public class MyX509TrustManager implements X509TrustManager { 
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null; 
    } 
}

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 教你如何編寫簡單的網(wǎng)絡爬蟲

    教你如何編寫簡單的網(wǎng)絡爬蟲

    實際的爬蟲是從一系列的種子鏈接開始。種子鏈接是起始節(jié)點,種子頁面的超鏈接指向的頁面是子節(jié)點(中間節(jié)點),對于非html文檔,如excel等,不能從中提取超鏈接,看做圖的終端節(jié)點
    2013-10-10
  • SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐記錄

    SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐記錄

    這篇文章主要介紹了SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-05-05
  • 高級數(shù)據(jù)結(jié)構(gòu)及應用之使用bitmap進行字符串去重的方法實例

    高級數(shù)據(jù)結(jié)構(gòu)及應用之使用bitmap進行字符串去重的方法實例

    今天小編就為大家分享一篇關(guān)于高級數(shù)據(jù)結(jié)構(gòu)及應用之使用bitmap進行字符串去重的方法實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • Java實現(xiàn)九宮格的簡單實例

    Java實現(xiàn)九宮格的簡單實例

    這篇文章主要介紹了 Java實現(xiàn)九宮格的簡單實例的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • SpringBoot與SpringCloud的版本對應關(guān)系解讀

    SpringBoot與SpringCloud的版本對應關(guān)系解讀

    本文介紹了SpringBoot與SpringCloud的版本對應關(guān)系,提供了一個官方的版本對應表,并給出了個人的一些經(jīng)驗總結(jié)
    2024-12-12
  • Java虛擬機如何運行Java字節(jié)碼

    Java虛擬機如何運行Java字節(jié)碼

    這篇文章主要介紹了Java虛擬機如何運行Java字節(jié)碼的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 使用JSONObject生成和解析json的方法

    使用JSONObject生成和解析json的方法

    下面小編就為大家?guī)硪黄褂肑SONObject生成和解析json的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 深入講解SpringBoot Actuator是什么

    深入講解SpringBoot Actuator是什么

    Spring Boot Actuator提供了生產(chǎn)上經(jīng)常用到的功能(如健康檢查,審計,指標收集,HTTP跟蹤等),幫助我們監(jiān)控和管理Spring Boot應用程序。這些功能都可以通過JMX或HTTP端點訪問
    2023-01-01
  • java高級用法之JNA中的回調(diào)問題

    java高級用法之JNA中的回調(diào)問題

    這篇文章主要介紹了java高級用法之:JNA中的回調(diào),為了方便和native方法進行交互,JNA中同樣提供了Callback用來進行回調(diào),JNA中回調(diào)的本質(zhì)是一個指向native函數(shù)的指針,通過這個指針可以調(diào)用native函數(shù)中的方法,一起來看看吧
    2022-05-05
  • Java多線程并發(fā)編程 Volatile關(guān)鍵字

    Java多線程并發(fā)編程 Volatile關(guān)鍵字

    volatile 關(guān)鍵字是一個神秘的關(guān)鍵字,也許在 J2EE 上的 JAVA 程序員會了解多一點,但在 Android 上的 JAVA 程序員大多不了解這個關(guān)鍵字。只要稍了解不當就好容易導致一些并發(fā)上的錯誤發(fā)生,例如好多人把 volatile 理解成變量的鎖
    2017-05-05

最新評論