随着中国互联网的发展,业务需求越来越复杂 。所有出现了许多做软件服务的公司,如: 阿里云、百度云、新浪、微信等等公司都推出了一系列的产品服务。这样给了小型公司带来福音。让开发者把精力放在了需求上面。
例如:以前的程序员开发一个邮箱发送的邮件的功能,他可能需要自己搭建一个邮箱服务器(麻烦),而现在的开发者只需要找到邮箱服务提供商(如:阿里云),然后对接他们的服务。
如何调用调用第三方接口( 本文案例:百度云文本审核)
百度云AI 接口地址
1.找到你需要调用的服务
2.选择使用
3.创建应用,获取调用接口的参数 ( 这里是 API Key ,Sercert Key ,其他服务商大致差不多)
4.找到接入文档
5.找到接口地址以及请求参数
这里content 参数是我们提供的需要审核的内容,access_token 是调用百度API的凭证
6.获取access_token
点击进去copy 获取access_token 的Java 代码
package com.baidu.ai.api.auth;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* @作者: tjx
* @描述: 获取access_token
* @创建时间: 创建于17:11 2018/9/7
**/
public class AuthService {
/**
* 获取权限token
* @return 返回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public static String getAuth() {
// 官网获取的 API Key 更新为你注册的
String clientId = "百度云应用的AK";
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = "百度云应用的SK";
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token
* 该token有一定的有效期,需要自行管理,当失效时需重新获取.
* @param ak - 百度云官网获取的 API Key
* @param sk - 百度云官网获取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public static String getAuth(String ak, String sk) {
// 获取token地址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
// 1. grant_type为固定参数
+ "grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + ak
// 3. 官网获取的 Secret Key
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 获取所有响应头字段
Map> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.err.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
System.err.println("result:" + result);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}
}
把创建时候获取的两个参数填进去调试下
7.封装API
7.1 封装结果Bean
/**
* Copyright 2018 bejson.com
*/
package com.baidu.ai.api.pojo;
import java.util.List;
/**
* Auto-generated: 2018-09-07 17:28:44
*
* @author bejson.com ([email protected])
* @website http://www.bejson.com/java2pojo/
*/
public class Pass {
private double score;
private List hit;
private int label;
public void setScore(double score) {
this.score = score;
}
public double getScore() {
return score;
}
public void setHit(List hit) {
this.hit = hit;
}
public List getHit() {
return hit;
}
public void setLabel(int label) {
this.label = label;
}
public int getLabel() {
return label;
}
}
/**
* Copyright 2018 bejson.com
*/
package com.baidu.ai.api.pojo;
import java.util.List;
/**
* Auto-generated: 2018-09-07 17:28:44
*
* @author bejson.com ([email protected])
* @website http://www.bejson.com/java2pojo/
*/
public class Result {
private int spam;
private List review;
private List reject;
private List pass;
public void setSpam(int spam) {
this.spam = spam;
}
public int getSpam() {
return spam;
}
public void setReview(List review) {
this.review = review;
}
public List getReview() {
return review;
}
public void setReject(List reject) {
this.reject = reject;
}
public List getReject() {
return reject;
}
public void setPass(List pass) {
this.pass = pass;
}
public List getPass() {
return pass;
}
}
/**
* Copyright 2018 bejson.com
*/
package com.baidu.ai.api.pojo;
/**
* Auto-generated: 2018-09-07 17:28:44
*
* @author bejson.com ([email protected])
* @website http://www.bejson.com/java2pojo/
*/
public class CheckTextResult {
private long log_id;
private Result result;
public void setLog_id(long log_id) {
this.log_id = log_id;
}
public long getLog_id() {
return log_id;
}
public void setResult(Result result) {
this.result = result;
}
public Result getResult() {
return result;
}
}
7.2 封装HttpClient
package com.utis;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* @作者: tjx
* @描述: http请求
* @创建时间: 创建于16:37 2018/9/7
**/
public class HttpUtil {
public static String doGet(String url, Map param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 请求的参数类型为json
* @param url
* @param json
* @return
* {username:"",pass:""}
*/
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}
7.3封装调用接口
package com.baidu.ai.api;
import com.baidu.ai.api.pojo.CheckTextResult;
import com.baidu.ai.api.pojo.Pass;
import com.baidu.ai.api.pojo.Result;
import com.utis.HttpUtil;
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* @作者: tjx
* @描述: 文本审核API
* @创建时间: 创建于17:19 2018/9/7
**/
public class CheckTextAPI {
private static final String URL = "https://aip.baidubce.com/rest/2.0/antispam/v2/spam";
/**
* @param content 需要审核的文本
*
* @return true 通过 false 失败
*/
public boolean check(String content){
//获取access_token
String access_token = AuthService.getAuth();
Map parameters = new HashMap<>();
//添加调用参数
parameters.put("access_token",access_token);
parameters.put("content",content);
//调用文本审核接口
String result = HttpUtil.doPost(URL, parameters);
// JSON转换
JSONObject jsonObj = JSONObject.fromObject(result);
Map classMap = new HashMap();
classMap.put("result",Result.class);
classMap.put("pass",Pass.class);
classMap.put("bass",CheckTextResult.class);
CheckTextResult bean = (CheckTextResult)JSONObject.toBean(jsonObj, CheckTextResult.class, classMap);
//根据API返回内容处理业务逻辑 (这里简单模拟,)
if(bean.getResult().getReject().size() + bean.getResult().getReview().size() > 0){
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println( new CheckTextAPI().check("你好"));
}
}
结果
市面上的大部分API服务商的接入方式都是这样的。