1. 程式人生 > >HttpClient傳送Post請求(一)

HttpClient傳送Post請求(一)

pom

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

code

package com.xxxxxx.xxxxx; 

import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/** 
 * @author wushucheng
 * @version 建立時間:2017年6月28日 下午5:20:23 
 * @TODO 類說明 
 */
public class HttpUtil {

    public static String post(String url, String body){

        String result = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
                client = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(url);
                StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8"));
                httpPost.setEntity(stringEntity);
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    return result;
    }

}

attention

以上程式碼可以傳送 http/https post 請求

呼叫微信API的時候,若body存在中文,一定要進行 UTF-8 轉碼,否則會報錯