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)文章
SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐記錄
這篇文章主要介紹了SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05高級數(shù)據(jù)結(jié)構(gòu)及應用之使用bitmap進行字符串去重的方法實例
今天小編就為大家分享一篇關(guān)于高級數(shù)據(jù)結(jié)構(gòu)及應用之使用bitmap進行字符串去重的方法實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02SpringBoot與SpringCloud的版本對應關(guān)系解讀
本文介紹了SpringBoot與SpringCloud的版本對應關(guān)系,提供了一個官方的版本對應表,并給出了個人的一些經(jīng)驗總結(jié)2024-12-12Java多線程并發(fā)編程 Volatile關(guān)鍵字
volatile 關(guān)鍵字是一個神秘的關(guān)鍵字,也許在 J2EE 上的 JAVA 程序員會了解多一點,但在 Android 上的 JAVA 程序員大多不了解這個關(guān)鍵字。只要稍了解不當就好容易導致一些并發(fā)上的錯誤發(fā)生,例如好多人把 volatile 理解成變量的鎖2017-05-05