原因:和别人对接,别人的接口是get请求参数从body中传入 (捶地大骂)
- 创建HttpGetWithEntity
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
import java.util.Date;
/**
* @author wdk
* @version 1.0.0
* @ClassName HttpGetWithEntity
* @Description TODO 定义一个带body的GET请求 继承 HttpEntityEnclosingRequestBase
* @createTime 2020.11.18 13:51
* @name
*/
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
private final static String METHOD_NAME = "GET";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
addHeader("Authorization", "Bearer "+token);
}
}
2.封装get请求
/**
* 发送get请求,参数为json
* @param url
* @param params 参数
* @return
* @throws Exception
*/
public static JSONObject sendJsonByGetReq(String url,Map<String,Object> params){
try {
String encoding = "UTF-8";
String param = JSONArray.toJSON(params).toString();
String body = "";
//创建httpclient对象
HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
httpGetWithEntity.setEntity(httpEntity);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = client.execute(httpGetWithEntity);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
//释放链接
response.close();
return JSONObject.parseObject(body);
}catch (Exception e){
e.printStackTrace();
}
return null;
}