Java GET请求 请求参数在Body中使用Json格式传参
业务需要调个三方接口
使用GET请求方式
但是!请求参数不在Query中,竟然在Body中,使用Json格式传参
在API调试工具里面可以调通
在java代码里,死活调不通
网上搜了搜,找到一个靠谱的,记录一下
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
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));
}
}
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.web.controller.tool.HttpGetWithEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Test {
public void test() throws Exception {
JSONObject params = new JSONObject();
params.put("systemToken","111");
params.put("userId","222");
params.put("timeout","333");
params.put("fileUrl","444");
HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity("http://*........");
httpGetWithEntity.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON));
httpGetWithEntity.setHeader("access-token","555");
httpGetWithEntity.setHeader("Content-Type","application/json");
CloseableHttpResponse response9 = HttpClients.createDefault().execute(httpGetWithEntity);
HttpEntity entity = response9.getEntity();
String result = "";
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
response9.close();
System.out.println(result);
}
}