介绍HttpClient库的使用前,先介绍jdk里HttpURLConnection,因为HttpClient是开源的第三方库,使用方便,不过jdk里的都是比较基本的,有时候没有HttpClient的时候也可以使用jdk里的HttpURLConnection,HttpURLConnection都是调jdk java.net库的,下面给出实例代码:

import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; public class Main {
public static void main(String[] args) throws Exception {
String url = "https://ocr-api.ccint.com/ocr_service?app_key=%s";
String appKey = "xxxxxx"; // your app_key
String appSecret = "xxxxxx"; // your app_secret
url = String.format(url, appKey);
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
String imgData = imageToBase64("example.jpg");
String param="{\"app_secret\":\"%s\",\"image_data\":\"%s\"}";
param=String.format(param,appSecret,imgData);
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // 设置请求方式
conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
out.close();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println(result);
}
public static String imageToBase64(String path)
{
String imgFile = path;
InputStream in = null;
byte[] data = null;
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}

然后介绍一下HttpClient,只给出实例代码,不封装成工具类,因为理解基本用法后,自己封装工具类也是很容易的

HttpClient的GET请求

   CloseableHttpClient httpClient = HttpClients.createDefault();
//https://github.com/search?utf8=%E2%9C%93&q=jeeplatform&type=
URIBuilder uriBuilder = new URIBuilder("https://github.com/search");
uriBuilder.addParameter("q","jeeplatform");
HttpGet httpGet = new HttpGet(uriBuilder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode==200){
HttpEntity entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity,"UTF-8"));
}
httpClient.close();
httpResponse.close();

HttpClient的POST请求,与GET请求类似

    CloseableHttpClient httpClient = HttpClients.createDefault();
//https://www.sogou.com/sie?query=%E8%8A%B1%E5%8D%83%E9%AA%A8&hdq=AQ7CZ&ekv=3&ie=utf8&
String uri = "https://www.sogou.com/sie";
List<NameValuePair> params= new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query","花千骨"));
StringEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode == 200){
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
}
httpClient.close();
httpResponse.close();

上面例子是可以支持访问签名要求没那么高的接口,然后访问自签名https的站点,那就要建立一个自定义的SSLContext对象,该对象要有可以存储信任密钥的容器,还要有判断当前连接是否受信任的策略,以及在SSL连接工厂中取消对所有主机名的验证,如果还是使用默认的HttpClient是会有下面的异常:

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

给出解决方法:

public static CloseableHttpClient getClient() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
// 指定信任密钥存储对象和连接套接字工厂
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// 信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
// 设置连接管理器
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_SECONDS * 1000).setConnectTimeout(TIMEOUT_SECONDS * 1000).build();
return HttpClientBuilder.create().setConnectionManager(connManager).setMaxConnTotal(POOL_SIZE).setMaxConnPerRoute(POOL_SIZE).setDefaultRequestConfig(requestConfig).build();
}

然后CloseableHttpClient httpClient = getClient()就可以

然后HttpClient语法相对比较繁杂?如果觉得比较麻烦,可以用Spring框架的RestTemplate,这里要创建一个自定义的bean,根据需要创建,代码示例:

//访问自签名https的要点
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(HttpClientUtil.getClient());
RestTemplate restTemplate = new RestTemplate(requestFactory);*/ Bean result= restTemplate.getForObject(digitalgdOauthUrl, Bean.class);

Http接口调用示例教程的更多相关文章

  1. 基于JAVA的全国天气预报接口调用示例

    step1:选择本文所示例的接口"全国天气预报接口" url:https://www.juhe.cn/docs/api/id/39/aid/87step2:每个接口都需要传入一个参 ...

  2. JAVA的免费天气api接口调用示例

    step1:选择本文所示例的接口"免费天气api" url:https://www.juhe.cn/docs/api/id/39/aid/87 step2:每个接口都需要传入一个参 ...

  3. node.js 接口调用示例

    测试用例git地址(node.js部分):https://github.com/wuyongxian20/node-api.git 项目架构如下: controllers: 文件夹下为接口文件 log ...

  4. .net短信接口调用示例(106短信通道)

    1. [代码]调用代理示例 using System;using System.Data;using System.Configuration;using System.Collections;usi ...

  5. OpenCV4Android开发之旅(一)----OpenCV2.4简介及 app通过Java接口调用OpenCV的示例

    转自:  http://blog.csdn.net/yanzi1225627/article/details/16917961 开发环境:windows+ADT Bundle+CDT+OpenCV-2 ...

  6. 快递鸟API接口调用代码示例(免费不限量)

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...

  7. 《C#微信开发系列(3)-获取接口调用凭据》

    3.0获取接口调用凭据 ①接口说明 access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.开发者需要进行妥善保存.access_token的存储至少要保留 ...

  8. 股票数据调用示例代码php

    <!--?php // +---------------------------------------------------------------------- // | JuhePHP ...

  9. WebService核心文件【server-config.wsdd】详解及调用示例

    WebService核心文件[server-config.wsdd]详解及调用示例 作者:Vashon 一.准备工作 导入需要的jar包: 二.配置web.xml 在web工程的web.xml中添加如 ...

随机推荐

  1. ABP开发框架前后端开发系列---(9)ABP框架的权限控制管理

    在前面两篇随笔<ABP开发框架前后端开发系列---(7)系统审计日志和登录日志的管理>和<ABP开发框架前后端开发系列---(8)ABP框架之Winform界面的开发过程>开始 ...

  2. js简单对象List自定义属性排序

    简单对象List自定义属性排序 <script type="text/javascript"> var objectList = new Array(); functi ...

  3. git上如何处理无法clone和merge

    对于一些需要FQ才能克隆下来的项目,我们需要使用代理 进入terminal: 设置代理: git config --global http.proxy http://127.0.0.1:1087 gi ...

  4. Shell学习笔记2》转载自runnoob

    学习且转载地址:http://www.runoob.com/linux/linux-shell-passing-arguments.html 这个网站整理的的确不错,看着很清晰,而且内容也很全面,个人 ...

  5. jQuery-ajax-.get,.post方法

    在上一篇中详细介绍了jQuery中ajax局部方法$.load()的使用.下面来介绍两个全局方法$.get(),$.post()的使用. 1.这两个全局方法其实和上一篇中的$.load()方法使用是差 ...

  6. (1)Linux文件系统的目录组成

    记忆秘诀:BBDEH OPRLM TLSUV 宝贝的恩惠 欧派入联盟 偷了suv,19   目录 英文释义 简写 详解 1 /   根目录 整个文件系统的唯一根目录 2 /bin Binary 普通命 ...

  7. Ubuntu 16.4-desktop系统安装显卡CUDA具体步骤!

    1.禁用nouveau驱动(切换至tty界面) sudo vim /etc/modprobe.d/blacklist.conf 在文本最后添加:blacklist nouveau options no ...

  8. ansible安装应用软件

    1.创建相应的目录: mkdir -p /ansible/roles/{nginx,mysql,tomcat,db,zabbix}/{defaults,files,handlers,meta,task ...

  9. android网络编程_socket(一)

    转载http://www.eoeandroid.com/thread-97477-1-1.html 小知识点:UDP协议和TCP协议的不同.UDP是把数据都打成数据包,数据包上自带通信的地址,但是数据 ...

  10. Java 新特性总结——简单实用

    lambda表达式 简介 lambda 表达式的语法 变量作用域 函数式接口 内置函数式接口 默认方法 Stream(流) 创建 stream Filter(过滤) Sorted(排序) Map(映射 ...