springMVC、https、GET调用别人提供的接口!!!
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpHost;
- import org.apache.http.HttpStatus;
- import org.apache.http.auth.AuthScope;
- import org.apache.http.auth.UsernamePasswordCredentials;
- import org.apache.http.client.CredentialsProvider;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.protocol.HttpClientContext;
- import org.apache.http.config.Registry;
- import org.apache.http.config.RegistryBuilder;
- import org.apache.http.conn.socket.ConnectionSocketFactory;
- import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
- import org.apache.http.conn.socket.PlainConnectionSocketFactory;
- import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
- import org.apache.http.conn.ssl.SSLContextBuilder;
- import org.apache.http.conn.ssl.SSLContexts;
- import org.apache.http.conn.ssl.TrustStrategy;
- import org.apache.http.impl.auth.BasicScheme;
- import org.apache.http.impl.client.BasicAuthCache;
- import org.apache.http.impl.client.BasicCredentialsProvider;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
- import org.apache.http.util.EntityUtils;
- import sun.net.www.protocol.http.AuthCache;
- import javax.net.ssl.SSLContext;
- import javax.swing.*;
- import java.io.IOException;
- import java.security.KeyManagementException;
- import java.security.KeyStore;
- import java.security.KeyStoreException;
- import java.security.NoSuchAlgorithmException;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- /**
- * Created by zml on 16-11-16.\
- * https的GET方式调用别人的接口,其实也可以用于http协议的,注意看代码的注释
- */
- public class HttpsGET {
- //如果给的链接是www.baidu.com这种域名而不是IP,就在cmd黑窗口ping一下域名就可以得到IP地址
- String ip = "xxxx.xxx.xx.xx";
- //如果给的链接没有端口号,则默认写为-1
- int port = -1;
- //接口调用所使用的协议
- String protocol = "https";
- String username = "zhangsan";
- String password = "password";
- public String httpsRequestsGet(String apiUrl){
- String responseBody = "";
- //注册协议并获取链接对象
- CloseableHttpClient httpClient = getHttpClient();
- HttpHost targetHost = new HttpHost(ip,port,protocol);
- //验证主机名端口号和用户名密码
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),
- new UsernamePasswordCredentials(username,password));
- org.apache.http.client.AuthCache authScope = new BasicAuthCache();
- BasicScheme basicScheme = new BasicScheme();
- authScope.put(targetHost,basicScheme);
- HttpClientContext context = HttpClientContext.create();
- context.setCredentialsProvider(credentialsProvider);
- context.setAuthCache(authScope);
- String url = protocol + "://" + ip + ":" + port + apiUrl;
- //GET方式调用接口
- HttpGet httpGet = new HttpGet(url);
- CloseableHttpResponse response = null;
- try {
- //链接目标主机,接收目标主机返回的对象
- response = httpClient.execute(targetHost,httpGet,context);
- } catch (IOException e) {
- e.printStackTrace();
- }
- int status = response.getStatusLine().getStatusCode();
- if(status== HttpStatus.SC_OK){
- HttpEntity entity = response.getEntity();
- try {
- responseBody = EntityUtils.toString(entity);
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- //关闭连接
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return responseBody;
- }
- private static CloseableHttpClient getHttpClient() {
- RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
- ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
- //注册http协议,如果不需要http协议就不需要写。
- registryBuilder.register("http",plainSF);
- //以下是注册https协议,与http不同的是多了证书的校验
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- TrustStrategy trustStrategy = new TrustStrategy() {
- @Override
- public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
- return true;
- }
- };
- SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, trustStrategy).build();
- //允许全部的证书,这样访问的时候就不用去校验证书是否可用。
- LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- //注册https协议
- registryBuilder.register("https",sslsf);
- } catch (KeyStoreException e) {
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- }
- Registry<ConnectionSocketFactory> registry = registryBuilder.build();
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
- return HttpClientBuilder.create().setConnectionManager(connManager).build();
- }
- }
所依赖的jar为
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.3.5</version>
- </dependency>
springMVC、https、GET调用别人提供的接口!!!的更多相关文章
- springMVC、httpClient调用别人提供的接口!!!(外加定时调用)
import com.ibm.db.util.AppConfig; import com.ibm.db.util.JacksonUitl; import org.apache.http.HttpEnt ...
- 调用别人提供的WebService
在开发过程中,许多时候需要使用到别人提供的WebService接口,使用其中的方法. 在调用别人提供的接口时,会得到接口使用的文档,其中包括接口的网络地址及方法作用等. 找到WebService的ws ...
- 如何调用别人提供的webservice接口
当我们拿到一个接口的时候,先别急着去调用它,我们得先测试这个接口是否正确,是否能调用成功,以及返回的数据是否是我们需要的类型等等.这时候我们需要一个工具,比如SoapUI.(最好用绿色免安装版的.)然 ...
- 如何调用别人提供的API?
1:一般使用聚合数据提供的API: 百度聚合数据,进入: 2:一般是有用户名的直接登录,没有用户名的先进行注册.在搜索框中输入你想查找的API方面的关键字:例如:有关健康的 点开任意一个,你将会看到: ...
- 通用的调用WebService的两种方法。(调用别人提供的wsdl)(转)
转载自:http://blog.sina.com.cn/s/blog_65933e020101incz.html1.调用WebService的Client端采用jax-ws调用WebService:流 ...
- jquery怎么实现跨域的访问呢?与别人提供的接口连接
下面这个例子你可以参考下 <script> $.ajax({ async:false, url: 'http://www.mysite.com/demo.do', // 跨域URL ty ...
- Spring Boot提供RESTful接口时的错误处理实践
使用Spring Boot开发微服务的过程中,我们会使用别人提供的接口,也会设计接口给别人使用,这时候微服务应用之间的协作就需要有一定的规范. 基于rpc协议,我们一般有两种思路:(1)提供服务的应用 ...
- java接口对接——调用别人接口推送数据
实际开发中经常会遇到要和其他平台或系统对接的情况,实际操作就是互相调用别人的接口获取或者推送数据, 当我们调用别人接口推送数据时,需要对方给一个接口地址以及接口的规范文档,规范中要包括接口的明确入参及 ...
- .net core 和 WPF 开发升讯威在线客服系统:调用有道翻译接口实现实时自动翻译的方法
业余时间用 .net core 写了一个在线客服系统.并在博客园写了一个系列的文章,写介绍这个开发过程. 我把这款业余时间写的小系统丢在网上,陆续有人找我要私有化版本,我都给了,毕竟软件业的初衷就是免 ...
随机推荐
- position:fixed失效
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- js中apply()和call()方法的使用
1.apply()方法 apply方法能劫持另外一个对象的方法,继承另外一个对象的属性. Function.apply(obj,args)方法能接收两个参数 obj:这个对象将代替Funct ...
- 关于用bootstrap显示查询的后台数据
PrintWriter pw = response.getWriter(); pw.println(sb); pw.flush(); 由于用bootstrap查询数据,页面需要自身返回bootstra ...
- yii2.0 框架邮件的发送
第一步: 在main-local.php中的components中配置mailer: $config = [ 'components' => [ 'mailer' => [ 'class' ...
- myEclipse svn插件安装
方法一(liuyou在安装时报空指针异常) 1.打开HELP->MyEclipse Configuration Center,切换到SoftWare标签页. 2.点击Add Site 打开对话框 ...
- ios显示或隐藏导航栏的底线
根据产品需求要求把这个界面导航栏的底线去掉,下个控制器还需要有底线. 使用下面的代码实现 //在页面出现的时候就将黑线隐藏起来 -(void)viewWillAppear:(BOOL)animated ...
- jetty 内嵌服务
pom.xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncodin ...
- mybatis动态sql
MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素. if choose(when,otherwise) trim(where,set) foreach 例子(2): &l ...
- vagrant安装及使用方法
http://www.chenjie.info/1757 http://blog.csdn.net/zsl10/article/category/6324870 --以下转自MaxWellDuva ...
- 对SIL9022/9024的配置
这里只是记录下对SIL9022.9024配置的I2C的数据,没有具体的程序.程序可以参考数据来做.程序官网也可能有. start of decoding Write to 0x72 0xBC ? 0x ...