Java如何实现调用外部Api

Java调用外部Api

在日常开发的时候,经常会遇到需要调用别人的接口的场景。但是每次需要的时候,都需要百度,很麻烦,所以这里总结一下,经常调用的方法。

1.含有文件的post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static String requestOCRForHttp(String url, Map requestParams, String filePathAndName)
        throws Exception {
    String result = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    /** HttpPost */
    HttpPost httpPost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(); // 建立多文件实例
    FileBody filebody = new FileBody(new File(filePathAndName));
    reqEntity.addPart("pic", filebody);// upload为请求后台的File upload;
    for (String key : requestParams.keySet()) {
        String value = requestParams.get(key);
        reqEntity.addPart(key, new StringBody(value, Charset.forName("utf-8")));
    }
    httpPost.setEntity(reqEntity); // 设置实体
    /** HttpResponse */
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    try {
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity, "utf-8");
        EntityUtils.consume(httpEntity);
    } finally {
        try {
            if (httpResponse != null) {
                httpResponse.close();
            }
        } catch (IOException e) {
            logger.info("## release resouce error ##" + e);
        }
    }
    return result;
}

2.单纯的Json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public static String sendHttpPost(String url, String JSONBody) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(JSONBody));
        CloseableHttpResponse response = httpClient.execute(httpPost);
//      System.out.println(response.getStatusLine().getStatusCode() + "n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
//      System.out.println(responseContent);
        response.close();
        httpClient.close();
        return responseContent;
    }

3.String参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    public static String requestOCRForHttp(String url, Map requestParams) throws Exception {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        /** HttpPost */
        HttpPost httpPost = new HttpPost(url);
        List params = new ArrayList();
        Iterator> it = requestParams.entrySet().iterator();
//      System.out.println(params.toString());
        while (it.hasNext()) {
            Entry en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            if (value != null) {
                params.add(new BasicNameValuePair(key, value));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        /** HttpResponse */
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "utf-8");
            EntityUtils.consume(httpEntity);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                logger.info("## release resouce error ##" + e);
            }
        }
        return result;
    }

Java对接外部API这个问题

有一个小学妹来问我可以将我其他项目的api接入到我现在的项目中吗?我回答“可以”!

需求提出

那么拿到一个需求首先话不多说先分析这个需求的整体思路!需求上面大概有介绍,这里我更深入化的说明一下。

对接外部api接口就是说我在A项目写了一个接口时我的B项目需要到A这个接口的数据,那么在A项目上线的基础上使用B项目去调用A项目的这个所需的接口,如下图:

其实对接外部api就是这么一个过程,当然我们拿到外部数据后面的操作都是由自己去自由发挥了,比如将读取到的数据来显示在这个项目中去给前端显示。或者存入数据库等等。

解决思路

上面已经理解了调用的的思路,有了思路就好解决,现在很多的外部api接口可以给开发时带来便利,当然,调用的方式可能也会有稍些不同,比如手机号查询归属地、邮箱等等。

像这种的一般都是有官方文档可以给我们,很方便。

但是我们去调用自己的api又不是在一个项目中的那就要想想怎么实现了。

话不多说我就拿我之前写了一个DEMO中的数据吧,刚好项目还在线上。

编码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package edu.controller;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.HttpMethod;
import edu.entity.EventVo;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @Author Fujii
 * @Date 2021-10-11 23:12
 * @Version SpringBoot 2.2.2
 * @projectName 调用外部api接口
 */
@RestController
public class BackEndApiDemo {
 
    @GetMapping("apiList")
    public Map getByApiList(){
        //这里先创建一个map用于返回api格式
        Map mapList = new HashMap();
        //1.我们是要去调用外部api,那么肯定要有一个外部api的地址,这里我是拿我的DEMO作为数据传输
        String apiURL = "这里直接放入你的api接口即可,我的api就不展示了,请谅解!";
        //2.这里有几种方式,你们去试了过后会发现不只有GET,这里因为我们是去获取数据,所以是用GET
        HttpMethod method = HttpMethod.GET;
        //用于接口返回的JSONObject()
        LinkedMultiValueMap map = new LinkedMultiValueMap();
        //json接收数据
        JSONObject  urlMethod = client(apiURL,method,map);
        JSONObject jsonObject = JSONObject.parseObject(urlMethod.toJSONString());
        JSONArray object = JSONObject.parseArray(jsonObject.get("data").toString());
        if (jsonObject!=null){
            List list = JSONArray.parseArray(object.toJSONString(), EventVo.class);
            mapList.put("list",list);
            mapList.put("code",200);
            mapList.put("msg", "获取成功!");
 
        }else{
            mapList.put("code",500);
            mapList.put("msg", "获取失败!");
            return mapList;
        }
        return mapList;
    }
     
    //注意:因为是测试,所有我所有内容全部写在一个文件内方便展示清晰,正规写法应写在服务层
    private JSONObject client(String url, HttpMethod method, LinkedMultiValueMap params) {
        RestTemplate template = new RestTemplate();
        ResponseEntity response = template.getForEntity(url, JSONObject.class);
        return response.getBody();
    }
}

测试

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/11147.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部