SpringBoot Maven项目调用第三方接口获取值
使用spring的restTemplate方式
- 引入依赖
1
2
3
4<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> - HttpClient工具类
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
29import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class HttpClient {
private RestTemplate restTemplate;
public <T> T doGet(String reqURL,Map<String,Object> params,Class<T> clazz){
//使用{}占位符,后面跟Object类型参数,这里使用Map<String,String>类型,里面存入了depotId
T t = restTemplate.getForEntity(reqURL, clazz, params).getBody();
return t;
}
/**
* doPost响应
* @param reqURL url链接
* @param params 入参实体
* @param clazz 响应实体
* @return
*/
public <T> T doPost(String reqURL, Object params, Class<T> clazz){
T t = restTemplate.postForEntity(reqURL, params, clazz).getBody();
return t;
}
} - RestTemplate配置
1
2
3
4
5
6
7
8
9
10
11
12import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
public class HttpClientRestTemplateConfig {
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
} - Controller接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import com.smart.Demo.domian.DemoEntity;
import com.smart.Demo.service.IDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
public class DemoController {
IDemoService demoService;
public DemoEntity Test(){
return demoService.getDemoEntity();
}
} - 业务逻辑层接口
1
2
3public interface IDemoService {
DemoEntity getDemoEntity();
} - 业务逻辑层实现
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
33import com.alibaba.fastjson.JSONObject;
import com.smart.Demo.common.R;
import com.smart.Demo.domian.DemoEntity;
import com.smart.Demo.util.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
public class DemoServiceImpl implements IDemoService{
private HttpClient httpClient;
public String url = "http://blog.renyuxin.cn";
public DemoEntity getDemoEntity() {
DemoEntity data = new DemoEntity();
try {
Map<String, Object> requestMap = new HashMap<>();
params.put("id", "123456");
R result = httpClient.doGet(url + "/getSoulSoup?id={id}", params, R.class);
System.out.println(result.getData());
// DemoEntity resultData = (DemoEntity) result.getData();
// 使用阿里的fastjson转格式,根据自己需求转格式
DemoEntity resultData = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), DemoEntity.class);
return resultData;
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
} - 实体类输出
1
2
3
4
5
6
7
8import lombok.Data;
public class DemoEntity {
private Integer id;
private String content;
private Integer hits;
}{
“id”:”1”,
“content”:”hello world”,
“hits”:”999”
}
使用HttpClient方式
- maven引入HttpClient依赖
1
2
3
4
5<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency> - HttpClient工具类
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* HttpClient工具类
*/
public class HttpClientUtil {
/**
* 发送post请求
* @param url 请求地址
* @param data 请求参数
* @return
*/
public static String doPost(String url,String data) {
CloseableHttpClient httpClient = HttpClients.createDefault();
//超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
.setConnectionRequestTimeout(10000) //请求超时
.setSocketTimeout(10000)
.setRedirectsEnabled(true) //允许自动重定向
.build();
if(url == null) {
return null;
}
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
if(data != null && data instanceof String) {
StringEntity stringEntity = new StringEntity(data,"UTF-8");
httpPost.setEntity(stringEntity);
}
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse != null) {
HttpEntity httpEntity = httpResponse.getEntity();
if(httpEntity != null) {
String result = EntityUtils.toString(httpEntity);
return result;
}
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 发送get请求
* @param url 请求地址
* @return
*/
public static String goGet(String url){
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.setRedirectsEnabled(true)
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
String jsonResult = EntityUtils.toString(httpResponse.getEntity());
return jsonResult;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
} - 调用工具类输出
1
2
3
4
5
6
7
8
9import com.smart.demo.util.HttpClientUtil;
public static String getAliJson() {
String bankId = "6222021608015631234";
//调用阿里校验银行卡接口
String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo=";
String json = HttpClientUtil.goGet(url + bankId);
return json;
}{
“cardType”:”DC”,
“bank”:”ICBC”,
“key”:”6222021608015631234”,
“messages”:[],
“validated”:true,
“stat”:”ok”
}
使用okhttp方式
- maven引入okhttp依赖
1
2
3
4
5
6
7<!-- okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.1</version>
<scope>compile</scope>
</dependency> - 编写okhttp通用类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttp {
public static String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("异常 " + response);
}
}
} - 调用okhttp方法输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import java.io.IOException;
import com.smart.model.util.OkHttp;
public String getAliJson() {
try {
String bankId = "6222021608015631234";
//调用阿里校验银行卡接口
String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo=";
String json = OkHttp.run(url + bankId);
return json;
} catch (IOException e) {
e.printStackTrace();
return "调用失败";
}
}{
“cardType”:”DC”,
“bank”:”ICBC”,
“key”:”6222021608015631234”,
“messages”:[],
“validated”:true,
“stat”:”ok”
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 学弟不想努力了!
评论