1. 程式人生 > >JAVA利用HttpClient進行POST請求

JAVA利用HttpClient進行POST請求

目前,要為另一個專案提供介面,介面是用HTTP URL實現的,最初的想法是另一個專案用JQuery post進行請求。

但是,很可能另一個專案是部署在別的機器上,那麼就存在跨域問題,而JQuery的post請求是不允許跨域的。

這時,就只能夠用HttpClient包進行請求了,同時由於請求的URL是HTTPS的,為了避免需要證書,所以用一個類繼承DefaultHttpClient類,忽略校驗過程。

package com.hellowin.yl.admin.util.httpUtil;

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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.rocketmq.common.utils.HttpTinyClient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

1.寫一個利用HttpClient傳送post請求的類
public class RequestClientInterface {
    private  CloseableHttpClient httpClient;

    public  RequestClientInterface() {
        // 1 建立HttpClinet,相當於開啟瀏覽器
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 帶引數的post請求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public  HttpTinyClient.HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 宣告httpPost請求
         HttpPost httpPost = new HttpPost(url);

        // 判斷map不為空
        if (map != null) {
            // 宣告存放參數的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍歷map,設定引數到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 建立form表單物件
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            formEntity.setContentType("Content-Type:application/json");

            // 把表單物件設定到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient發起請求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 解析response封裝返回物件httpResult
        HttpTinyClient.HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpTinyClient.HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpTinyClient.HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回結果
        return httpResult;
    }
}


2.呼叫post請求的測試程式碼
import java.util.HashMap;
import java.util.Map;
    //對介面進行測試
    public class TestMain {
        private String url = "https://192.168.1.101/";
        private String charset = "utf-8";
        private HttpClientUtil httpClientUtil = null;

        public TestMain(){
            httpClientUtil = new HttpClientUtil();
        }

        public void test(){
            String httpOrgCreateTest = url + "httpOrg/create";
            Map<String,String> createMap = new HashMap<String,String>();
            RequestClientInterface clientInterface = new RequestClientInterface();
            createMap.put("orgname","****");
            createMap.put("functionId", "****");
            HttpTinyClient.HttpResult httpResult = clientInterface.doPost(httpOrgCreateTest, createMap);
            System.out.println("result:"+httpResult);
        }

        public static void main(String[] args){
            TestMain main = new TestMain();
            main.test();
        }
    }