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;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章