踩坑Apache HttpEntity

package com.qianbaocard.vinci.tc.web.rest.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LiSenMao on 2018/5/5.
 */
@Component
public class HttpClientUtil {

    public static final String CHARSET = "UTF-8";

    public static String doPostKeyValue(String url, Map<String, String> map) {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost;
        CloseableHttpResponse response = null;
        String result = null;
        try {
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<>();
            map.forEach((k, v) -> list.add(new BasicNameValuePair(k, v)));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, CHARSET);
            /*
            * 注意,一定要加,默认就是application/x-www-form-urlencoded,但是、但是、但是
            * 不加,服务器收不到参数
            * */
            entity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(entity);

            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, CHARSET);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "xxx");
        map.put("access_token", "xxx");
        map.put("machine_code", "xxx");

        System.out.println(doPostKeyValue("https://xxx", map));
    }
}

去看UrlEncodedFormEntity的源码:

    /**
     * Constructs a new {@link UrlEncodedFormEntity} with the list
     * of parameters in the specified encoding.
     *
     * @param parameters list of name/value pairs
     * @param charset encoding the name/value pairs be encoded with
     * @throws UnsupportedEncodingException if the encoding isn't supported
     */
    public UrlEncodedFormEntity (
        final List <? extends NameValuePair> parameters,
        final String charset) throws UnsupportedEncodingException {
        super(URLEncodedUtils.format(parameters,
                charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name()),
                ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
    }

接着查看CONTENT_TYPE :

    /**
     * The default HTML form content type.
     */
    public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";

没搞明白,为什么默认参数就是application/x-www-form-urlencoded,还非要我去指定一下,不然,服务器就接收不到参数。

猜你喜欢

转载自my.oschina.net/maomaolsm/blog/1807258