利用Apache HttpClient或PHP curl发送带Body的GET请求

By | 2019年4月25日

一、需求

今天对接某IDC运营商API的时候,发现一直没有对接成功。然后使用API文档中的PHP示例进行调试,请求响应是成功的。

通过wireshark进行抓包对比,发现请求参数是放在body中的,而不是使用QueryString的方式。如下图:

二、API文档中使用PHP Curl发送带Body GET请求的实现

function request($url, $data = array(), $method = 'GET')
{
    
    $str       = http_build_query($data);
    //请求头
    //$header = array();
    $ch     = curl_init(); //初始化CURL句柄
    curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头信息
    curl_setopt($ch, CURLOPT_POSTFIELDS, $str);//设置提交的字符串

    $result = curl_exec($ch);//执行预定义的CURL
    return !(bool)curl_errno($ch) ? (array)json_decode($result, 1) : false;
}

三、使用JAVA Apache HttpClient实现发送带Body的GET请求

3.1、自定义HttpGetWithEntity类
package com.renyiwei.beans;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {

    public final static String METHOE_NAME = "GET";
    @Override
    public String getMethod() {
        return METHOE_NAME;
    }
}
3.2、调用HttpGetWithEntity发送带Body的GET请求
private String doRequest(String url, Map<String,String> params, RequestMethod method)throws Exception{
        
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
        HttpGetWithEntity httpGet = new HttpGetWithEntity();
        httpGet.setURI(new URI(url));
        //自定义请求头
        //httpGet.addHeader("X-HTTP-Method-Override",method.toString());
        httpGet.setEntity(urlEncodedFormEntity);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        httpClient.close();
        return responseString;
    }

四、参考文档

 https://blog.csdn.net/liehuoruge91/article/details/78437076

https://stackoverflow.com/questions/12535016/apache-httpclient-get-with-body