时间:2021-05-20
1、前文:通过webService发送https请求,有两种版本,一种是携带证书验证(比较麻烦),另外一种就是直接忽略证书,本文提供的就是第二种(本人已测试过)
2、最简易代码:
import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import java.net.MalformedURLException;import java.net.URL;import java.text.SimpleDateFormat;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLSession;@SuppressWarnings("all")public class TestAPI_https { public static void main(String args[]) throws Exception { new TestAPI_https().TestRiQingAPI_SaleOrder(); } public static void TestRiQingAPI_SaleOrder() throws Exception { String postData = getJson(); //String url = "https://*****"; String url = "https://*****"; HttpsURLConnection conn = null; OutputStream out = null; String rsp = null; byte[] byteArray = postData.getBytes("utf-8"); try { URL uri = new URL(url); conn = (HttpsURLConnection) uri.openConnection(); //忽略证书验证--Begin conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); //忽略证书验证--End conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Host", uri.getHost()); conn.setRequestProperty("Content-Type", "application/json"); out = conn.getOutputStream(); out.write(byteArray); out.close(); if(conn.getResponseCode()==200) { rsp = getStreamAsString(conn.getInputStream(), "utf-8"); }else { rsp = getStreamAsString(conn.getErrorStream(), "utf-8"); } System.out.println(rsp); } catch (Exception e) { if(null!=out) out.close(); e.printStackTrace(); } } /** * getJson * */ private static String getJson() { return "{" + "\"name\"" + ":" + "\"robo_blogs_zh123\"" + "}"; } private static String getStreamAsString(InputStream stream, String charset) throws IOException { try { Reader reader = new InputStreamReader(stream, charset); StringBuilder response = new StringBuilder(); final char[] buff = new char[1024]; int read = 0; while ((read = reader.read(buff)) > 0) { response.append(buff, 0, read); } return response.toString(); } finally { if (stream != null) { stream.close(); } } }}//定制Verifierclass TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求,实例代码:packa
如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。Java有原生的API可用于发送HTTP请求,即java.net.U
一、前言如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。Java有原生的API可用于发送HTTP请求,即java.n
java向服务端发送GET和POST请求复制代码代码如下:packagecom.hongyuan.test;importjava.io.BufferedRead
本文实例为大家分享了C#wx获取token的具体代码,供大家参考,具体内容如下#region请求Url,不发送数据//////请求Url,不发送数据///pub