基于java调用https接口

时间:2025-03-23 10:43:43
两种方式:
1:使用 jar包:
package ;
import ;
import ;
import .X509Certificate;
import ;
import ;
import .X509TrustManager;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/*
 * 测试类(比较完善)
 * 测试Https接口 post
 *https接口的调用与http有些不同
 *  * apache官网可以下载最新的jar包和demo
 * /
 */
public class TestSampleUpload4clientHttps {
 public static void main(String[] args) throws Exception {
  CloseableHttpClient closeableHttpClient = createHttpsClient();
  // 建立HttpPost对象
  HttpPost httppost = new HttpPost(" https://192.168.:8443/XXXXX/XXXX/");
  // 配置要 POST 的数据begin
  MultipartEntityBuilder multipartEntityBuilder = ();
  // 设置为浏览器兼容模式  
  (HttpMultipartMode.BROWSER_COMPATIBLE); 
  // 设置请求的编码格式
  ((HTTP.UTF_8));
  ContentType TEXT_PLAIN = ("text/plain", (HTTP.UTF_8));
  ("userName", "admin",TEXT_PLAIN);
  ("psd", "admin",TEXT_PLAIN);
  ("mac", "abw3232jjf2swsj3",TEXT_PLAIN);
  ("md5", "uy0kfwefess8e6",TEXT_PLAIN);
  ("type", "sample",TEXT_PLAIN);
  //文件路径
  File file = new File("D:\\glpt\\");
  ("file", file);
  // 配置要 POST 的数据end
  // 生成 HTTP POST 实体
  HttpEntity httpEntity = ();
  (httpEntity);
  //发送Post,并返回一个HttpResponse对象
  HttpResponse httpResponse = (httppost);
  HttpEntity httpEntity2 = ();
  ("().getStatusCode():"+().getStatusCode());
  // 如果状态码为200,就是正常返回
  if (().getStatusCode() == HttpStatus.SC_OK) {
   String result = (httpEntity2);
   // 得到返回的字符串
   (result);
   // 如果是下载文件,可以用().getContent()返回InputStream
  }else {
   String result = (httpEntity2);
   // 得到返回的字符串
   (result);
  }
  //关闭连接
  ();
  
 }
 public static CloseableHttpClient createHttpsClient() throws Exception   {
  X509TrustManager x509mgr = new X509TrustManager() {
   @Override
   public void checkClientTrusted(X509Certificate[] xcs, String string) {
   }
   @Override
   public void checkServerTrusted(X509Certificate[] xcs, String string) {
   }
   @Override
   public X509Certificate[] getAcceptedIssuers() {
    return null;
   }
  };
  SSLContext sslContext = ("TLS");
  (null, new TrustManager[] { x509mgr }, new ());
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    sslContext,
    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  return ().setSSLSocketFactory(sslsf).build();
 }
 
}

相关文章