前言
现在公司业务已止不是传统的增删改查等简单的业务处理操作,而是对数据各种联调三方接口与其他系统进行交互等,那么就需要我们在后台java中进行外部接口的调用,本文采用OkHttps工具类对接微信接口为大家简单介绍下,java调用外部接口进行数据交互。
第一步新建接口Demo
本文采用Idea作为开发工具
依次按照 file---new---project
紧接着如下
如果这样写就会提示
因为Idea中创建项目-项目名称必须小写
接着继续勾选Jar依赖
Jar依赖选择完成之后,确认项目名称跟所在目录
更具体的步骤请查看公众号之前写的
学习栈新年献礼-SpringBoot第一弹
项目创建好之后,创建两个package,用来存放我们的工具类,与接口
先引入项目所需jar包依赖
buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'com.ahdd99.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-jdbc'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'mysql:mysql-connector-java'
compile 'org.springframework.boot:spring-boot-starter-test'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
compile 'com.xiaoleilu:hutool-all:3.1.0'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
compileOnly 'org.projectlombok:lombok:1.16.6'
testCompile 'org.springframework.boot:spring-boot-starter-test'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
providedRuntime 'org.apache.tomcat:tomcat-jasper:8.5.28'
}
紧接着,在util包里面引入我们的okhttps工具类
OkHttps工具类中主要封装了get与post请求,这里简单让大家看下,源代码会贴在文章末尾
/**
* OkHttpUtils 工具类
*/
@Slf4j
public class OkHttpUtils {
private final static OkHttpClient client = new OkHttpClient().newBuilder()
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
public static JsonObject doGetRetJson(String url) throws IOException {
return doGetRetJsonElement(url).getAsJsonObject();
}
public static JsonElement doGetRetJsonElement(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
return sendSyncRequestRetJsonElement(request);
}
public static JsonObject doPostRetJson(String url, String jsonBody) throws IOException {
return doPostRetJsonElement(url, jsonBody).getAsJsonObject();
}
public static JsonElement doPostRetJsonElement(String url, String jsonBody) throws IOException {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
Request request = new Request.Builder().url(url).post(requestBody).build();
return sendSyncRequestRetJsonElement(request);
}
public static String doPostRetJsonString(String url, String jsonBody) throws IOException {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
Request request = new Request.Builder().url(url).post(requestBody).build();
return sendSyncRequestRetString(request);
}
public static String doPostRetString(String url, String textBody) throws IOException {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), textBody);
Request request = new Request.Builder().url(url).post(requestBody).build();
return sendSyncRequestRetString(request);
}
public static void doPost(String url, Map<String, String> params) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (String key : params.keySet()) {
formBuilder.add(key, params.get(key));
}
Request request = new Request.Builder().url(url).post(formBuilder.build()).build();
sendSyncRequestRetString(request);
}
public static JsonObject doPostRetJson(String url, Map<String, String> params) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (String key : params.keySet()) {
formBuilder.add(key, params.get(key));
}
Request request = new Request.Builder().url(url).post(formBuilder.build()).build();
return sendSyncRequestRetJson(request);
}
/**
* 支付宝请求返回form
*
* @param url
* @param params
* @return
* @throws IOException */
public static String doPostResString(String url, Map<String, String> params) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
for (String key : params.keySet()) {
formBuilder.add(key, params.get(key));
}
Request request = new Request.Builder().url(url).post(formBuilder.build()).build();
return sendSyncRequestRetString(request);
}
public static JsonObject doPostRetJsonForUploadFile(String url, Map<String, Object> params) throws IOException {
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
params.forEach((key, value) -> {
if (value instanceof File) {
File file = (File) value;
formBuilder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("application/pdf; charset=utf-8"), file));
} else {
formBuilder.addFormDataPart(key, value.toString());
}
});
Request request = new Request.Builder().url(url).post(formBuilder.build()).build();
return sendSyncRequestRetJson(request);
}
private static JsonObject sendSyncRequestRetJson(Request request) throws IOException {
return sendSyncRequestRetJsonElement(request).getAsJsonObject();
}
private static JsonElement sendSyncRequestRetJsonElement(Request request) throws IOException {
return JsonUtils.toJsonElement(sendSyncRequestRetString(request));
}
private static String sendSyncRequestRetString(Request request) throws IOException {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("请求出错,出错信息:" + response.message());
}
String retString = response.body().string();
if (StrUtil.isEmpty(retString)) {
return "";
}
return retString;
}
}
kHttps工具类引入完成之后,引入JsonUtils工具类,这个主要是帮助我们吧参数封给JSON,免去我们在每个接口中再进行单独封装
/**
* 参数转json工具类
*/
public class JsonUtils {
private static final JsonParser JSON_PARSER = new JsonParser();
public static String toJson(Object object) {
Gson gson = new GsonBuilder().create();
return gson.toJson(object);
}
public static JsonObject toJsonObject(String json) {
return JSON_PARSER.parse(json).getAsJsonObject();
}
public static JsonArray jsonObjectToJsonArray(JsonObject jsonObject) {
JsonArray jsonArray = new JsonArray();
jsonArray.add(jsonObject);
return jsonArray;
}
public static JsonElement toJsonElement(String json) {
return JSON_PARSER.parse(json);
}
}
工具类都引入完毕之后,就是我们的重头戏了
接口开发第一步,抽离接口Api工具类
将所有的接口路径抽离为工具类,并且定义为常量,方便后期维护
/**
* 接口api路径
* @author gyk
* @date 2019-03-27 11:27
*/
public class WxPortApi {
/**
* 接口请求路径
*/
public final static String WX_API = "https://api.weixin.qq.com";
/**
* 学习栈appID
*/
public final static String WX_APP_ID = "";
/**
* 学习栈AppSecret
*/
public final static String AppSecret = "";
/**
* 获取access_token接口
*/
public final static String ACCESS_TOKEN = "/cgi-bin/token";
}
下来就是接口调用
创建package service
编写接口service层业务处理
/**
* 获取公众号的access_token
* @param appId --- 微信appId
* @param secret --- 微信秘钥
* @return
*/
public JsonObject getAccessTocken(String appId, String secret){
JsonObject resultJson = new JsonObject();
Map<String, String> params = new HashMap<>(3);
//赋值接口需传递参数
//获取access_token填写client_credential
params.put("grant_type", "client_credential");
// 第三方用户唯一凭证
params.put("appid", appId);
// 第三方用户唯一凭证密钥,即appSecret
params.put("secret", secret);
try {
//调用okHttps工具类进行接口调用
return OkHttpUtils.doPostRetJson(WxPortApi.WX_API + WxPortApi.ACCESS_TOKEN, params);
} catch (IOException e) {
//赋值失败结果
resultJson.addProperty("result","-1");
resultJson.addProperty("msg",msg +"获取access_token失败");
return resultJson;
}
}
然后编写单元测试
/**
* 测试获取公众号的access_token
*/
@Test
public void getAccessTocken() {
WxPortService wxPortService = new WxPortService();
JsonObject jsonObject = wxPortService.getAccessTocken(WxPortApi.WX_APP_ID, WxPortApi.AppSecret);
//获取错误码
String error_code = String.valueOf(jsonObject.get("errcode"));
//如果errcode 为空,那么证明获取的正确,不然获取失败
if("null".equals(error_code)){
//打印得到的access_token
System.out.println(String.valueOf(jsonObject.get("access_token")));
}
}
在这里有一个小坑大家要注意,java中String.valueOf() 如果你传入的是NULL 那么java会给你返回"Null" 字符串
剩下的微信接口对接将于后面进一步详细讲解
添加小编微信,加入技术交流群or招聘交流群
QQ千人技术交流群: 710566091 一起学习一起成长
源码地址 https://gitee.com/DaiDaiDeXiaoMaNong/port.git
来源:oschina
链接:https://my.oschina.net/u/4303621/blog/3303847