HttpsURLConnection 使用样例

本文介绍了一种使用Java的HttpsURLConnection类进行HTTPS请求的方法,详细展示了如何设置请求头,处理SSL证书验证,以及读取响应内容的过程。通过一个具体的示例,演示了向平安ICORE PTS平台的登录接口发送GET请求的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void testHttpConnetion() {
  try {
    //https://icore-pts.pingan.com.cn/ebusiness/login.do
    URL url = new URL("https://icore-pts.pingan.com.cn/ebusiness/login.do");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setConnectTimeout(30000);
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);
    //Host: icorepnbs.pingan.com.cn
    con.setRequestProperty("Host","icorepnbs.pingan.com.cn");
    con.setRequestProperty("Origin","https://icorepnbs.pingan.com.cn");
    //Accept: */*
    con.setRequestProperty("Accept","*/*");
    //Accept-Encoding: gzip, deflate, br
    con.setRequestProperty("Accept-Encoding","gzip, deflate, br");
    //Accept-Language: zh-CN,zh;q=0.9
    con.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
    //User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
    //X-Requested-With: ShockwaveFlash/29.0.0.171
    con.setRequestProperty("X-Requested-With","ShockwaveFlash/29.0.0.171");
    String cookies = "";
    List<Cookie> cookies1 = getHttpExecutor().getCookieStore().getCookies();
    for (Cookie cookie : cookies1) {
      cookies += cookie.getName() + "=" + cookie.getValue() + ";";
    }

    String substring = cookies.substring(0, cookies.length() - 1);
    con.setRequestProperty("Cookie", substring);

    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[]{};
      }

      public void checkClientTrusted(X509Certificate[] chain, String authType)
          throws CertificateException {
      }

      public void checkServerTrusted(X509Certificate[] chain, String authType)
          throws CertificateException {
      }
    }};

    try {
      SSLContext sc = SSLContext.getInstance("TLS");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      SSLSocketFactory newFactory = sc.getSocketFactory();
      con.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
      e.printStackTrace();
    }

    int code = con.getResponseCode();
    if(code == 200) {
      System.out.println("调用成功");
      InputStream inputStream2 = con.getInputStream();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] data = new byte[2048];
      int len = 0;
      while ((len = inputStream2.read(data)) != -1) {
        bos.write(data, 0, len);
      }
      inputStream2.close();
      String content = bos.toString();
      System.out.println(content);
    }
    StringBuffer buffer = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    System.out.println(br.toString());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
您可以按照以下步骤将上述代码改造为调用https的接口: 1. 将wsdl地址中的http替换成https,即将以下代码: call.setTargetEndpointAddress("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl"); 改为: call.setTargetEndpointAddress("https://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl"); 2. 创建SSLContext实,并设置信任管理器TrustManager来信任所有证书: ```java import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; //... TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { } } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); ``` 3. 设置HttpsURLConnection默认的SSLSocketFactory和HostnameVerifier: ```java import javax.net.ssl.HttpsURLConnection; //... HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> true); ``` 4. 将调用方式改为使用HttpURLConnection,即将以下代码: String result = (String) call.invoke(new Object[]{"13999903152"}); 改为: URL url = new URL("https://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); connection.setDoOutput(true); String soapRequest = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">\n" + " <mobileCode>13999903152</mobileCode>\n" + " <userID></userID>\n" + " </getMobileCodeInfo>\n" + " </soap:Body>\n" + "</soap:Envelope>"; OutputStream outputStream = connection.getOutputStream(); outputStream.write(soapRequest.getBytes("UTF-8")); String result = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) { StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } result = stringBuilder.toString(); } System.out.println(result); ``` 请注意替换代码中的mobileCode参数值和soapRequest中的namespace和方法名。同时,为了保证代码的安全性,请在实际使用过程中,不要信任所有证书,可以使用合法的证书或者自己实现TrustManager来进行证书校验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值