java模拟http请求header里加application/x-www-form-urlencoded的方式

 java模拟http请求header里加application/x-www-form-urlencoded的方式

public String post(String url,Map<String,String> map) {
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("grant_type", map.get("grant_type")));
    urlParameters.add(new BasicNameValuePair("client_id", map.get("client_id")));
    urlParameters.add(new BasicNameValuePair("client_secret", map.get("client_secret")));
    urlParameters.add(new BasicNameValuePair("code", map.get("code")));
    urlParameters.add(new BasicNameValuePair("redirect_uri", map.get("redirect_uri")));
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    HttpPost post = new HttpPost(url);
    post.addHeader("Content-Type","application/x-www-form-urlencoded");
    try {
        post.setEntity(new UrlEncodedFormEntity(urlParameters, HTTP.UTF_8));
        try {
            response = httpclient.execute(post);
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.printf("=============="+content);
                return content;
            }
            EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } finally {
        //释放链接
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值