Post x-www-form-urlencoded数据

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

public static String postUrlEncodeForm(String url,Map<String,Object> map,String coding) throws Exception {
        if (null == coding || "".equals(coding)) {
            coding = DEFAULT_CODING;
        }
        
        String result = "";
        
        //处理请求参数
        List<NameValuePair> valuePairs = new ArrayList<>();
        for(Entry<String,Object> entry : map.entrySet()) {
            NameValuePair valuePair = new BasicNameValuePair(entry.getKey(), toString(entry.getValue()));
            valuePairs.add(valuePair);
        }
        
        //设置client参数
        HttpClient client = HttpClientBuilder.create().build();
        
        //发送请求
        HttpPost post = new HttpPost(url);
        HttpEntity entity = new UrlEncodedFormEntity(valuePairs,coding);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        
        //处理响应结果
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new RuntimeException("statusCode = [" + statusCode + "]");
        } else {
            HttpEntity respEntity = response.getEntity();
            result = EntityUtils.toString(respEntity,coding);
        }
        return result;
    }

猜你喜欢

转载自my.oschina.net/u/2611678/blog/1923938
今日推荐