欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java发送https请求代码实例

程序员文章站 2023-11-24 20:53:10
1、前文:通过webservice发送https请求,有两种版本,一种是携带证书验证(比较麻烦),另外一种就是直接忽略证书,本文提供的就是第二种(本人已测试过) 2、最简...

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

}

//定制verifier
class trustanyhostnameverifier implements hostnameverifier {
  public boolean verify(string hostname, sslsession session) {
    return true;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。