search
HomeJavajavaTutorialExample of how Java uses HttpClient to call the HTTPS interface

This article mainly introduces the method of JAVA using HttpClient to make HTTPS interface calls. It has certain reference value. Those who are interested can learn about it.

This article introduces the method of JAVA using HttpClient to make HTTPS interface calls. Share with everyone, the details are as follows:

1. In order to avoid the need for a certificate, use a class to inherit the DefaultHttpClient class and ignore the verification process.


import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 用于进行Https请求的HttpClient 
 * @ClassName: SSLClient 
 * @Description: TODO
 * @author Devin <xxx> 
 * @date 2017年2月7日 下午1:42:07 
 * 
 */
public class SSLClient extends DefaultHttpClient {
  public SSLClient() throws Exception{
    super();
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain,
            String authType) throws CertificateException {
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain,
            String authType) throws CertificateException {
        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return null;
        }
    };
    ctx.init(null, new TrustManager[]{tm}, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = this.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
  }
}

2. Create a tool class that uses HttpClient to send post requests


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
/**
 * 利用HttpClient进行post请求的工具类
 * @ClassName: HttpClientUtil 
 * @Description: TODO
 * @author Devin <xxx> 
 * @date 2017年2月7日 下午1:43:38 
 * 
 */
public class HttpClientUtil {
  @SuppressWarnings("resource")
  public static String doPost(String url,String jsonstr,String charset){
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try{
      httpClient = new SSLClient();
      httpPost = new HttpPost(url);
      httpPost.addHeader("Content-Type", "application/json");
      StringEntity se = new StringEntity(jsonstr);
      se.setContentType("text/json");
      se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
      httpPost.setEntity(se);
      HttpResponse response = httpClient.execute(httpPost);
      if(response != null){
        HttpEntity resEntity = response.getEntity();
        if(resEntity != null){
          result = EntityUtils.toString(resEntity,charset);
        }
      }
    }catch(Exception ex){
      ex.printStackTrace();
    }
    return result;
  }
}

3. Test code


public static void main(String[] args){ 
    String url = "https://192.168.1.101/xxx";
    String jsonStr = "{xxx}";
    String httpOrgCreateTestRtn = HttpClientUtil.doPost(url, jsonStr, "utf-8");
  }

The above is the detailed content of Example of how Java uses HttpClient to call the HTTPS interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何使用golang中的http.Client进行HTTP请求的高级操作如何使用golang中的http.Client进行HTTP请求的高级操作Nov 18, 2023 am 11:37 AM

如何使用golang中的http.Client进行HTTP请求的高级操作引言:在现代开发中,HTTP请求是不可避免的一部分。golang提供了强大的标准库,其中包含了http包。http包提供了http.Client结构体,用于发送HTTP请求和接收HTTP响应。在本文中,我们将探讨如何使用http.Client进行HTTP请求的高级操作,并提供具体的代码示

使用Java 11中的HttpClient发送HTTP请求并处理响应使用Java 11中的HttpClient发送HTTP请求并处理响应Aug 01, 2023 am 11:48 AM

标题:使用Java11中的HttpClient发送HTTP请求并处理响应引言:在现代的互联网应用程序中,与其他服务器进行HTTP通信是非常常见的任务。Java提供了一些内置的工具,可以帮助我们实现这一目标,其中最新且推荐使用的是Java11中引入的HttpClient类。本文将介绍如何使用Java11中的HttpClient发送HTTP请求并处理响应,

如何使用Java中的httpclient进行重定向和请求转发的比较如何使用Java中的httpclient进行重定向和请求转发的比较Apr 21, 2023 pm 11:43 PM

这里介绍一下:HttpClient4.x版本,get请求方法会自动进行重定向,而post请求方法不会自动进行重定向,这是要注意的地方。我上次发生错误,就是使用post提交表单登录,当时没有自动重定向。请求转发和重定向的区别1、重定向是两次请求,转发是一次请求,因此转发的速度要快于重定向。2、重定向之后地址栏上的地址会发生变化,变化成第二次请求的地址,转发之后地址栏上的地址不会变化,还是第一次请求的地址。3、转发是服务器行为,重定向是客户端行为。重定向时浏览器上的网址改变,转发是浏览器上的网址不变

Nginx下如何升级httpsNginx下如何升级httpsMay 14, 2023 pm 04:49 PM

下载证书在证书控制台下载nginx版本证书。下载到本地的压缩文件包解压后包含:.pem文件:证书文件.key文件:证书的私钥文件(申请证书时如果没有选择自动创建csr,则没有该文件)配置nginx1、在nginx的安装目录下创建cert目录,并且将下载的全部文件拷贝到cert目录中,如果申请证书时是自己创建的csr文件,请将对应的私钥文件放到cert目录下。2、打开nginx安装目录下conf目录中的nginx.conf文件#usernobody;worker_processes1;#error

nginx如何让浏览器强制跳转HTTPS访问nginx如何让浏览器强制跳转HTTPS访问May 15, 2023 pm 02:34 PM

效果可以看如下:但是如果我们现在使用http来访问的话,访问不了。如下图所示:因此我现在首先要做的是使用nginx配置下,当用户在浏览器下输入http请求的时候使用nginx重定向到https下即可。因此我们现在需要做一个简单的nginx重定向功能。因此在我们的nginx中需要加如下重定向配置:server{listenxxx.abc.com;server_namexxx.abc.com;rewrite^/(.*)$https://$host$1permanent;}因此nginx主要的配置代码

Nginx如何将HTTP重定向到HTTPSNginx如何将HTTP重定向到HTTPSMay 13, 2023 am 09:52 AM

Nginx是一个强大的重定向工具,可以轻松配置在您的系统上重定向不安全或未加密的HTTP网络流量到加密和安全的HTTPS网络服务器。Nginx,发音为“Enginex”,是一个免费、开源、基于Linux的高性能Web和反向代理服务器,负责管理和处理互联网上最大的网站流量的负载。Nginx是一个强大的重定向工具,可以轻松配置在您的系统上重定向不安全或未加密的HTTP网络流量到加密和安全的HTTPS网络服务器。如果你是一个系统管理员或开发人员,那么你应该经常使用Nginx服务器。在这篇文章中,我们将

nginx如何配置SSL证书实现https服务nginx如何配置SSL证书实现https服务May 15, 2023 pm 03:25 PM

假如我现在node基本架构如下:|----项目||---static#存放html文件|||---index.html#index.html||---node_modules#依赖包||---app.js#node入口文件||---package.json||---.babelrc#转换es6文件index.html文件代码如下:nginx配置https欢迎使用https来访问页面app.js代码如下:constkoa=require(&#39;koa&#39;);constfs

Nginx服务器https如何配置Nginx服务器https如何配置May 23, 2023 am 11:01 AM

申请证书目前网上有不少机构提供个人免费ssl证书,有效期几个月到几年不等。以startssl:https://www.startssl.com为例,申请成功后有效期3年,到期后可免费续租。具体申请过程也很简单。注册登录以后选择certificateswizard>>dvsslcertificate申请一个免费的ssl证书。通过邮件验证域名之后,然后在自己服务器中生成ssl证书的csr,记住生成输入的秘密,之后要用到:opensslreq-newkeyrsa:2048-keyoutwe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!