HTTP get请求发送JSON格式数据

1,603 阅读1分钟

get请求一般不建议发送JSON格式的数据,单总有一些奇葩系统要求

分享下本人对接途牛 传递get请求 json数据的方法

第一步:平常的get请求不要想了 直接继承

 
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);
    }
    HttpGetWithEntity(final String uri) {
        super();
        setURI(URI.create(uri));
    }
}

第二步

    public String getDataToJson(String var1, String jsonText) {
        String var4 = null;
        CloseableHttpClient var5 = HttpClients.createDefault();
        try {
            HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(var1);
            HttpEntity httpEntity = new StringEntity(jsonText, ContentType.APPLICATION_JSON);
            httpGetWithEntity.setEntity(httpEntity);
            CloseableHttpResponse response = var5.execute(httpGetWithEntity);
           /** 此步自己处理返回结果 我这里有个工具类 所以不要复制了
           *  可以使用  HttpEntity httpEntity = httpResponse.getEntity();
           *  result = EntityUtils.toString(var1, "UTF-8")
           */
            var4 = responseToResult(response);
        } catch (Exception e) {
            log.error("调用get请求Error:" + e.getMessage());
            e.printStackTrace();
        }
        return var4;
    }

这样就可以了

即使这样解决了get 加body 体传参,但是仍建议大家使用post方式发送JSON格式数据