前言

   现在公司业务已止不是传统的增删改查等简单的业务处理操作,而是对数据各种联调三方接口与其他系统进行交互等,那么就需要我们在后台java中进行外部接口的调用,本文采用OkHttps工具类为大家简单介绍下,java调用外部接口进行数据交互。

第一步新建接口Demo

    本文采用Idea作为开发工具  

    依次按照 file---new---project

java两个项目之间接口查询 java跨项目调用接口_spring boot

  紧接着如下

java两个项目之间接口查询 java跨项目调用接口_java_02

  如果这样写就会提示

  因为Idea中创建项目-项目名称必须小写

java两个项目之间接口查询 java跨项目调用接口_intellij-idea_03

接着继续勾选Jar依赖

java两个项目之间接口查询 java跨项目调用接口_intellij-idea_04

Jar依赖选择完成之后,确认项目名称跟所在目录

java两个项目之间接口查询 java跨项目调用接口_intellij-idea_05

项目创建好之后,创建两个package,用来存放我们的工具类,与接口

java两个项目之间接口查询 java跨项目调用接口_java_06

先引入项目所需jar包依赖

dependencies {
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
    compile group: 'commons-codec', name: 'commons-codec', version: '1.10'
    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.24'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
    compile group: 'org.springframework.boot', name: 'spring-boot-devtools'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
    compile group: 'net.coobird', name: 'thumbnailator', version: '0.4.7'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile 'com.xiaoleilu:hutool-all:3.1.0'
    compile 'joda-time:joda-time:2.9.9'
    compileOnly 'org.projectlombok:lombok:1.16.6'
    testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
    providedRuntime group: 'org.apache.tomcat', name: 'tomcat-jasper', version: '8.5.4'
    providedRuntime group: "org.springframework.boot", name: 'spring-boot-starter-tomcat'
}

紧接着,在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工具类

将所有的接口路径抽离为工具类,并且定义为常量,方便后期维护

java两个项目之间接口查询 java跨项目调用接口_java两个项目之间接口查询_07

接下来就是接口调用

创建package service

编写接口service层业务处理

/**
 * 用户登录接口
 * @param userAccount --- 用户账号
 * @param userPwd  --- 用户密码
 * @return
 */
public JsonObject userLogin(String userAccount, String userPwd){
    Map<String, String> params = new HashMap<>(3);
    //赋值接口需传递参数
    params.put("loginName", userAccount);
    params.put("password", userPwd);
    try {
        //调用okHttps工具类进行接口调用
        return OkHttpUtils.doPostRetJson(ThirdPortApi.PORT_API + ThirdPortApi.USER_LOGIN_API, params);
    } catch (IOException e) {
     JsonObject jsonObject = new JsonObject();
     jsonObject.addProperty("result","-1");
     jsonObject.addProperty("msg",msg +"用户登录接口");
     return jsonObject;
    }
}

后面就是启动单元测试工具测试,然后根据接收参数进行业务处理

将于后面进一步详细讲解