目录
- 0.碎碎念
- 1.controller层
- 2.util层
- 3.测试
- 3.1中间层调用GET请求
- 3.2中间层调用POST请求
0.碎碎念
因为只是为了写这个帮助类,解耦,不敢拿已经写了一堆的代码改,就单独拆了个项目出来,持久层全是mybatisplus生成的。
所以就只展示核心的部分,代码也会传到csdn的资源里。
其实可以用Feign,但是没学透不敢用,怕太费时间,这个算是比较简单又快的解耦方式了。
1.controller层
被调用的接口
/**
* 根据id查询
* service层没查询到直接返回null
* @param gatewayId
* @return
*/
@GetMapping("getGatewayById/{gatewayId}")
public R getGatewayById(@PathVariable(value = "gatewayId") Long gatewayId){
DvcGateway gateway = dvcGatewayService.getGatewayById(gatewayId);
Map<String, Object> map = new HashMap<>();
if(gateway == null){
map.put("msg", "查询单个网关失败");
return R.ok(map);
}else {
map.put("gateway", gateway);
map.put("msg", "ok");
return R.ok(map);
}
}
/**
* 查询所有的网关信息(不分页)
* 给其他接口调用使用
* @return
*/
@PostMapping("/listGateway")
public R listGateway(){
List<DvcGateway> dvcGatewayList = dvcGatewayService.listGateway("");
if(dvcGatewayList.isEmpty()){
//如果没有查询到数据
return R.error();
}else {
Map<String, Object> map = new HashMap<>();
map.put("gatewayList", dvcGatewayList);
//给调用接口查询是否成功的标识
map.put("msg", "ok");
return R.ok(map);
}
}
调用的接口
package com.csdn.selma.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.csdn.selma.pojo.DvcGateway;
import com.csdn.selma.pojo.R;
import com.csdn.selma.util.HttpRequestHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/test")
public class TestController {
@Value("${myConfig.api}")
private String api;
@PostMapping("/callGet")
public R callGet(){
//测试调用@GetMapping("getGatewayById/{gatewayId}")
Map<String, Object> paramMap = new HashMap<>();
JSONObject result = HttpRequestHelper.sendRequestByGet(api + "/gateway/getGatewayById/" + 1);
if("ok".equals(result.getString("msg"))) {
Map<String, Object> map = new HashMap<>();
DvcGateway gateway = JSON.toJavaObject(result.getJSONObject("gateway"), DvcGateway.class);
map.put("dvcGateway", gateway);
return R.ok(map);
}
return R.error();
}
@PostMapping("/callPost")
public R callPost(){
//测试调用@PostMapping("/listGateway")
Map<String, Object> paramMap = new HashMap<>();
JSONObject result = HttpRequestHelper.sendRequestByPost(paramMap, api + "/gateway/listGateway");
if("ok".equals(result.get("msg"))) {
Map<String, Object> map = new HashMap<>();
List<DvcGateway> gatewayList = (List<DvcGateway>) result.get("gatewayList");
map.put("gatewayList", gatewayList);
return R.ok(map);
}
return R.error();
}
}
2.util层
第一层调用
package com.csdn.selma.util;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
@Slf4j
public class HttpRequestHelper {
/**
* 封装同步请求POST
* @param paramMap
* @param url
* @return
*/
public static JSONObject sendRequestByPost(Map<String, Object> paramMap, String url){
String result = "";
try {
//封装post参数
StringBuilder postdata = new StringBuilder();
for (Map.Entry<String, Object> param : paramMap.entrySet()) {
postdata.append(param.getKey()).append("=")
.append(param.getValue()).append("&");
}
log.info(String.format("--> 发送请求:post data %1s", postdata));
byte[] reqData = postdata.toString().getBytes("utf-8");
//调方法发送请求
byte[] respData = HttpUtil.doPost(url, reqData);
result = new String(respData);
log.info(String.format("--> 应答结果:result data %1s", result));
} catch (Exception ex) {
ex.printStackTrace();
}
return JSONObject.parseObject(result);
}
/**
* 封装同步请求GET
* @param url
* @return
*/
public static JSONObject sendRequestByGet(String url){
String result = "";
try {
log.info(String.format("--> 发送请求:get url %1s", url));
//调方法发送请求
byte[] respData = HttpUtil.doGet(url);
result = new String(respData);
log.info(String.format("--> 应答结果:result data %1s", result));
} catch (Exception ex) {
ex.printStackTrace();
}
return JSONObject.parseObject(result);
}
}
第二层调用
package com.csdn.selma.util;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class HttpUtil {
static final String POST = "POST";
static final String GET = "GET";
static final int CONN_TIMEOUT = 30000;// ms
static final int READ_TIMEOUT = 30000;// ms
/**
* post 方式发送http请求.
*
* @param strUrl
* @param reqData
* @return
*/
public static byte[] doPost(String strUrl, byte[] reqData) {
return send(strUrl, POST, reqData);
}
/**
* get方式发送http请求.
*
* @param strUrl
* @return
*/
public static byte[] doGet(String strUrl) {
return send(strUrl, GET, null);
}
/**
* @param strUrl
* @param reqmethod
* @param reqData
* @return
*/
public static byte[] send(String strUrl, String reqmethod, byte[] reqData) {
try {
URL url = new URL(strUrl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setDoInput(true);
httpcon.setUseCaches(false);
httpcon.setInstanceFollowRedirects(true);
httpcon.setConnectTimeout(CONN_TIMEOUT);
httpcon.setReadTimeout(READ_TIMEOUT);
httpcon.setRequestMethod(reqmethod);
httpcon.connect();
if (reqmethod.equalsIgnoreCase(POST)) {
OutputStream os = httpcon.getOutputStream();
os.write(reqData);
os.flush();
os.close();
}
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"utf-8"));
String inputLine;
StringBuilder bankXmlBuffer = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
bankXmlBuffer.append(inputLine);
}
in.close();
httpcon.disconnect();
return bankXmlBuffer.toString().getBytes();
} catch (Exception ex) {
log.error(ex.toString(), ex);
return null;
}
}
}
3.测试
使用postman软件测试
3.1中间层调用GET请求
按照实际调用改接口和参数即可。
3.2中间层调用POST请求
按照实际调用改接口和参数即可。