當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
java通过HTTPS协议POST提交接收JSON格式数据
生活随笔
收集整理的這篇文章主要介紹了
java通过HTTPS协议POST提交接收JSON格式数据
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 一、客戶(hù)端實(shí)現(xiàn)
- 1. HttpsApiUtils +測(cè)試方法
- 2. 返回報(bào)文監(jiān)控
- 二、服務(wù)端實(shí)現(xiàn)
- 2.1. 配置SSL 實(shí)現(xiàn)HTTPS
- 2.2. 添加post接口方法
- 2.3. 服務(wù)端監(jiān)控
- 三、進(jìn)階測(cè)試
- 3.1. 客戶(hù)端發(fā)送對(duì)象
- 3.2. 服務(wù)端監(jiān)控
- 3.3. 客戶(hù)端解析返回報(bào)文
一、客戶(hù)端實(shí)現(xiàn)
聲明:不用引入任何第三方j(luò)ar包,只需要安裝JDK即可,目前版本適配1.6及以上版本
1. HttpsApiUtils +測(cè)試方法
package com.gblfy.util;import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;/*** 實(shí)現(xiàn)HTTPS協(xié)議POST請(qǐng)求JSON報(bào)文** @author gblfy* @date 2020-06-19*/public class HttpsApiUtil {private static class TrustAnyTrustManager implements X509TrustManager {// 該方法檢查客戶(hù)端的證書(shū),若不信任該證書(shū)則拋出異常。由于我們不需要對(duì)客戶(hù)端進(jìn)行認(rèn)證,因此我們只需要執(zhí)行默認(rèn)的信任管理器的這個(gè)方法。// JSSE中,默認(rèn)的信任管理器類(lèi)為T(mén)rustManager。@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}/** 該方法檢查服務(wù)器的證書(shū),若不信任該證書(shū)同樣拋出異常。通過(guò)自己實(shí)現(xiàn)該方法,可以使之信任我們指定的任何證書(shū)。* 在實(shí)現(xiàn)該方法時(shí),也可以簡(jiǎn)單的不做任何處理, 即一個(gè)空的函數(shù)體,由于不會(huì)拋出異常,它就會(huì)信任任何證書(shū)。(non-Javadoc)*/@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}// 返回受信任的X509證書(shū)數(shù)組。@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[]{};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}}/*** post方式請(qǐng)求服務(wù)器(https協(xié)議)** @param url 求地址* @param content 參數(shù)* @param charset 編碼* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/public static byte[] sendJsonToHttpsPost(String url, String content,String charset) throws NoSuchAlgorithmException,KeyManagementException, IOException {/** 類(lèi)HttpsURLConnection似乎并沒(méi)有提供方法設(shè)置信任管理器。其實(shí),* HttpsURLConnection通過(guò)SSLSocket來(lái)建立與HTTPS的安全連接* ,SSLSocket對(duì)象是由SSLSocketFactory生成的。* HttpsURLConnection提供了方法setSSLSocketFactory* (SSLSocketFactory)設(shè)置它使用的SSLSocketFactory對(duì)象。* SSLSocketFactory通過(guò)SSLContext對(duì)象來(lái)獲得,在初始化SSLContext對(duì)象時(shí),可指定信任管理器對(duì)象。*/SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);// 設(shè)置請(qǐng)求頭conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、關(guān)閉out.flush();out.close();InputStream is = conn.getInputStream();if (is != null) {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();return outStream.toByteArray();}return null;}public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException {String url = "https://127.0.0.1:8888/postToJson";byte[] bytes = sendJsonToHttpsPost(url, "{\"name\":\"ly\"}", "utf-8");System.out.println("響應(yīng)報(bào)文:"+new String(bytes));} }2. 返回報(bào)文監(jiān)控
解析
通過(guò)上述方式可以得到收發(fā)方法post()。傳入字符串,返回字節(jié)數(shù)組。
傳入的字符串處理:
JSONObject rspObj = new JSONObject(); rspObj.put("arg1", "aaa"); rspObj.put("arg2", "bbb"); //... String reqStr = rspObj.toString(); System.out.println("請(qǐng)求json:\n" + reqStr);返回的字節(jié)數(shù)組轉(zhuǎn)字符串:
byte[] result = post(reqUrl,reqStr,"utf-8"); if(result != null){String rspStr = new String(result);System.out.println("響應(yīng)json:\n" + rspStr); }二、服務(wù)端實(shí)現(xiàn)
2.1. 配置SSL 實(shí)現(xiàn)HTTPS
Spring Boot 配置SSL 實(shí)現(xiàn)HTTPS
2.2. 添加post接口方法
package com.gblfy.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;@Controller @RequestMapping public class ViewControlller {@RequestMapping(value = "/postToJson", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")@ResponseBodypublic String postToJson(@RequestBody String json) {System.out.println("https服務(wù)端接收到報(bào)文:" + json);return json;} }2.3. 服務(wù)端監(jiān)控
三、進(jìn)階測(cè)試
3.1. 客戶(hù)端發(fā)送對(duì)象
package com.gblfy.pojo;import java.io.Serializable;public class User implements Serializable {private String username;private Integer age;private String passwd;public User(String username, Integer age, String passwd) {this.username = username;this.age = age;this.passwd = passwd;}public User() {}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getPasswd() {return passwd;}public void setPasswd(String passwd) {this.passwd = passwd;} } public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException, JSONException {//1. 模擬對(duì)象發(fā)送User user = new User();user.setUsername("gblfy");user.setAge(28);user.setPasswd("123456");//2. 配置發(fā)送urlString url = "https://127.0.0.1:8888/postToJson";//3.發(fā)送前將對(duì)象轉(zhuǎn)json處理JSONObject jsonObject = new JSONObject(user);String reqXml = jsonObject.toString();//4.向指定url發(fā)送json格式的https協(xié)議報(bào)文byte[] bytes = sendJsonToHttpsPost(url, reqXml, "utf-8");//5.對(duì)返回的報(bào)文解析String resXml = new String(bytes);JSONObject jsonObj = new JSONObject(resXml);//6.從解析的報(bào)文中獲取指定的值System.out.println("服務(wù)端返回報(bào)文:" + jsonObj.getString("username"));System.out.println("服務(wù)端返回報(bào)文:" + jsonObj.getInt("age"));System.out.println("服務(wù)端返回報(bào)文:" + jsonObj.getString("passwd"));}3.2. 服務(wù)端監(jiān)控
https服務(wù)端接收到報(bào)文:{"passwd":"123456","age":28,"username":"gblfy"}3.3. 客戶(hù)端解析返回報(bào)文
服務(wù)端返回報(bào)文:gblfy 服務(wù)端返回報(bào)文:28 服務(wù)端返回報(bào)文:123456總結(jié)
以上是生活随笔為你收集整理的java通过HTTPS协议POST提交接收JSON格式数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java 实现Https访问工具类 跳过
- 下一篇: Flowable 数据库表结构 ACT_