项目中需要在接口内部访问另一个接口,在这里使用jodd工具包来实现,相对来说比较简单
1.引入jodd-http的依赖
org.jodd jodd-http 3.6.2
2.编写工具类,实现get/post请求的发送
package com.uticket.common.util;
import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
@Slf4j
public class HttpUtil {
private static final ObjectMapper mapper = new ObjectMapper();
public static String sendHttpGet(String url, Map params) throws Exception {
HttpRequest request = HttpRequest.get(url);
if(!CollectionUtil.isEmpty(params)){
request.query(params);
}
HttpResponse response = request.send();
String bodyText = response.bodyText();
bodyText = transFormToUtf8(bodyText);
return bodyText;
}
public static String sendHttpPostJosn(String url, Map params){
HttpRequest request = HttpRequest.post(url);
request.contentType("application/json");
request.charset("utf-8");
if(!CollectionUtil.isEmpty(params)){
try {
request.body(mapper.writevalueAsString(params));
} catch (JsonProcessingException e) {
log.error("write paramter [" + params.toString() + "] to josn fail",e.getMessage(),e);
}
}
HttpResponse response = request.send();
return response.bodyText();
}
public static String sendHttpPost(String url, Map params){
HttpRequest request = HttpRequest.post(url);
if(!CollectionUtil.isEmpty(params)) {
request.form(params);
}
HttpResponse response = request.send();
return response.bodyText();
}
private static String transFormToUtf8(String source) throws Exception{
return new String(source.getBytes(),"utf-8");
}
}
3.测试类
String url = "";
String result = null;
try {
result = HttpUtil.sendHttpGet(url, null);
} catch (Exception e) {
log.error("查询失败....." + url,e.getMessage(),e);
}
System.out.println(result);



