1.pom依赖

     <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.15</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.2.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-util</artifactId><version>9.3.7.v20160115</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.5</version><scope>test</scope></dependency>

2.工具类

 public static Object bookSearch(String isbn) {String host = "https://isbn.market.alicloudapi.com";String path = "/ISBN";String method = "GET";String appcode = "自己买的api的appcode";Map<String, String> headers = new HashMap<String, String>();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);Map<String, String> querys = new HashMap<String, String>();querys.put("is_info", "0");querys.put("isbn", isbn);Map<String, Object> map = new HashMap<>();try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);System.out.println(response.toString());//获取response的bodyString str = EntityUtils.toString(response.getEntity(), "UTF-8");JSONObject jsonObject = JSONObject.parseObject(str);System.out.println(jsonObject);map.put("result", jsonObject);return map;} catch (Exception e) {e.printStackTrace();}return map;}

3.HttpUtil

package org.fh.controller.book;import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpUtils {/*** get** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doGet(String host, String path, String method,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpGet request = new HttpGet(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form** @param host* @param path* @param method* @param headers* @param querys* @param bodys* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,Map<String, String> bodys)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");request.setEntity(formEntity);}return httpClient.execute(request);}/*** Post String** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Post stream** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Put stream** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doDelete(String host, String path, String method,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpDelete request = new HttpDelete(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {StringBuilder sbUrl = new StringBuilder();sbUrl.append(host);if (!StringUtils.isBlank(path)) {sbUrl.append(path);}if (null != querys) {StringBuilder sbQuery = new StringBuilder();for (Map.Entry<String, String> query : querys.entrySet()) {if (0 < sbQuery.length()) {sbQuery.append("&");}if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {sbQuery.append(query.getValue());}if (!StringUtils.isBlank(query.getKey())) {sbQuery.append(query.getKey());if (!StringUtils.isBlank(query.getValue())) {sbQuery.append("=");sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));}}}if (0 < sbQuery.length()) {sbUrl.append("?").append(sbQuery);}}return sbUrl.toString();}private static HttpClient wrapClient(String host) {HttpClient httpClient = new DefaultHttpClient();if (host.startsWith("https://")) {sslClient(httpClient);}return httpClient;}private static void sslClient(HttpClient httpClient) {try {SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] xcs, String str) {}public void checkServerTrusted(X509Certificate[] xcs, String str) {}};ctx.init(null, new TrustManager[]{tm}, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx);ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = httpClient.getConnectionManager();SchemeRegistry registry = ccm.getSchemeRegistry();registry.register(new Scheme("https", 443, ssf));} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}}
}

Java调用外部api接口请求数据(阿里云ISBN查询图书信息为例)相关推荐

  1. Java调用 新浪微博API 接口发微博(包含js微博组件、springMVC新浪登录)详解

    参考自:http://www.myexception.cn/program/1930025.html https://blog.csdn.net/qq_36580777/article/details ...

  2. Java调用 新浪微博API 接口发微博,逐项讲解,绝对清晰

    转载自:http://www.myexception.cn/program/1930025.html Java调用 新浪微博API 接口发微博,逐条讲解,绝对清晰 最近要做个课程设计,使用微博控制树莓 ...

  3. Java调用 新浪微博API 接口发微博,逐条讲解,绝对清晰

    最近要做个课程设计,使用微博控制树莓派,树莓派再控制发光二极管的亮和灭,主要设计分两层,上层是用Java调用新浪微博API来实现对微博旳监听,当我的微博被回复时能够自动读取评论内容,并根据评论的指令内 ...

  4. 调用万维易源API接口请求数据

    万维易源官方地址 万维易源-互联网API入口一次接入,调用全部.将一切数据API化.万维易源是一个统一了通讯协议的API总线,互联网接口调用的入口,高度安全,超高性能,海量接口资源.https://w ...

  5. java调用别人的接口获取数据存到mysql数据库

    1.根据接口返回的字段创建数据库表 2.创建对应这个表的controller,service,mapper,pojo 3.在controller层调用Impl实现类.具体业务:接收数据并保存在数据库, ...

  6. 如何使用API接口批量查询图书信息?

    之前小编讲过在Excel表格中根据ISBN查询图书信息可以使用我们的图书查询公式,但偶然间发现少部分书籍由于年份久远导致查不出来,今天小编就教给大家另一种查询图书信息的方式,即通过API接口返回的JS ...

  7. java跨域权重_爱站权重查询 API 接口请求调用

    原标题:爱站权重查询 API 接口请求调用 爱站权重查询 API 接口在网上已经很多且大都封装成了 API 供别人调用.支持前台跨域请求,以GET/POST方式提交即可.爱站权重查询 API 接口可以 ...

  8. php 抓取360搜索数据,360搜索收录 API 接口请求调用

    原标题:360搜索收录 API 接口请求调用 360收录 API 接口在网上已经很多且大都封装成了 API 供别人调用.支持前台跨域请求,以GET/POST方式提交即可.360收录 API 接口可以查 ...

  9. JAVA 短信API接口调用 附 文档 Demo

    JAVA 短信API接口调用 附 文档 Demo 1.请求地址 http://host:port/sms 请求方式可以 POST 和 GET方式,建议采用POST方式 2.参数说明 参数需要 URLE ...

  10. 如何利用python调用API接口获取数据进行测试

    一.Python 可以使用 requests 库来调用 API 接口获取数据.以下是基本的步骤: 1.安装 requests 库 pip install requests 2.导入 requests ...

最新文章

  1. BS-XX-026 基于SpringBoot 实现个人理财系统
  2. java注释跳转方法,Java自定义注解实现Router跳转
  3. [ARM-assembly]-全局变量/静态全局变量/初始化/未初始化变量的存放位置分析
  4. 骚年快答 | 技术中台与业务中台都是啥?
  5. 5gh掌上云计算认证不通过_【众志成城战疫情】法官助理告诉你“移动微法院”、“掌上法庭”有多便捷、有多硬核~!...
  6. 学成在线--4.CMS页面管理开发(新增页面)
  7. python变量和对象,切片列表元祖
  8. AS3的一些压缩解压缩类库(AS3 ZIP、AS3 GZIP等等)
  9. onerror捕获异常
  10. 实用的在线文本分析工具
  11. 第二章节:期货市场组织结构与投资者
  12. 全面了解三极管——三极管基本参数2
  13. ai条码插件免安装_Illustrator条形码插件
  14. python复制上一行到下一行_eclipse复制当前行到下一行-eclipse复制-eclipse复制一行快捷键...
  15. win7加入网络计算机,win7怎么加入局域网工作组_win7加入局域网工作组的步骤
  16. linux 终端tty的含义,终端、控制台、tty、shell等区别与概念初辨析
  17. [TcaplusDB|黎明觉醒] 一路相伴,不负期待
  18. 集团版固定资产管理系统方案
  19. 简单精干之 MyBatis-Plus
  20. PTA——基础编程题 | 7-27 冒泡法排序 (20分)

热门文章

  1. 微信小程序getLocation定位偏差问题
  2. 使用谷歌地图拾取异国坐标
  3. Jmeter 接口造数
  4. java 自动点击按钮事件_JavaScript代码模拟鼠标自动点击事件示例
  5. 微信小程序 之修改switch组件尺寸大小
  6. 计算机管理格式化硬盘,细说电脑怎么格式化硬盘
  7. React修改图片大小
  8. zigbee网关 CC2530 zstack用手机显示终端传来的lm75a温度传感器的值
  9. 怎么打开计算机开机启动菜单,计算机怎么添加多系统启动菜单?电脑添加双系统启动菜单的方法...
  10. 学习感悟(人脸识别)