springboot使用HttpClient调用聚合数据第三方接口(get方法)

首先,引入依赖:


            org.apache.httpcomponents
            httpclient
            4.5.12
        

然后,编写一个HttpClientUtil类,该类的代码如下:

package com.springboot.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.net.URI;
import java.util.Map;
@Component
public class HttpClientUtil {

    public static String doGet(String url, Map param) {

        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = 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 result;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

}

接着,就可以在controller类中调用接口,我这里调用的是聚合数据网的根据身份证查询area的接口,并将其值填入到user表中:

@PostMapping("/add")
    @Transactional(readOnly = false)
    public void addUser(@Valid User user,Integer u_rid,Integer u_did){

        String key="xxxxxxxxx";
        String url="http://apis.juhe.cn/idcard/index"+"?key="+key+"&cardno="+user.getCardId();
        String result=httpClientUtil.doGet(url);
        JSONObject jso= JSON.parseObject(result);
        JSONObject jsa=JSON.parseObject(jso.getString("result"));
        String area=jsa.getString("area");
        user.setArea(area);
        userService.addUser(user);
    }

其中使用fastjson将string转换成对象并提取area值的方法详见我的上一篇博客。
此时用postman测试,发现add成功,数据库中自动存储了area信息。
springboot使用HttpClient调用聚合数据第三方接口(get方法)_第1张图片
在这里插入图片描述

你可能感兴趣的:(学海漂游)