温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java如何发送https请求

发布时间:2020-07-16 14:42:59 来源:亿速云 阅读:219 作者:小猪 栏目:编程语言

这篇文章主要为大家展示了Java如何发送https请求,内容简而易懂,下面让小编带大家一起学习一下吧。

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_zh223\"" + "}";
  }

  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();
      }
    }
  }

}

//定制Verifier
class TrustAnyHostnameVerifier implements HostnameVerifier {
  public boolean verify(String hostname, SSLSession session) {
    return true;
  }
}

以上就是关于Java如何发送https请求的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI