1. 程式人生 > >java 通過後端訪問http並傳參之post傳參

java 通過後端訪問http並傳參之post傳參

String param= "{\n" +
        "\"signature\":\"1b811b104815e80dc06204769abf019454918820\",\n" +
        "\"timestamp\":\"636132491337817532\",\n" +
        "\"nonce\":\"0978730774\",\n" +
        "\"action\":\"GET_LIST\",\n" +
        "\"appid\":\"dsfew45432544dfs23q4rt5\",\n" +
        "\"accountname\":\"\",\n" +
        "\"data\":{\n" +
        "\"entity_type\":\"RESERVATION\",\n" +
        "\"pageindex\":0,\n" +
        "\"pagesize\":20,\n" +
        "\"query_condition\":{\n" +
        "\"starttime\":\"2015-1-31T16:00:00Z\",\n" +
        "\"endtime\":\"2018-12-31T16:00:00Z\",\n" +
        "\"key\":\"\",\n" +
        "\"name\":\"\"\n" +
        "}\n" +
        "}\n" +
        "}";
// 獲取預設的請求客戶端
CloseableHttpClient client = HttpClients.createDefault();
// 通過HttpPost來發送post請求
HttpPost httpPost = new HttpPost("http://10.10.20.114:8090/api/tt/post");
/*
 * post帶引數開始
 */
// 第三步:構造list集合,往裡面丟資料
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = new BasicNameValuePair("param", param);
pairs.add(pair);
// 第二步:我們發現Entity是一個介面,所以只能找實現類,發現實現類又需要一個集合,集合的泛型是NameValuePair型別
try {
    httpPost.setEntity(new UrlEncodedFormEntity(pairs,"utf8"));
    /*
     * post帶引數結束
     */
    // HttpEntity
    // 是一箇中間的橋樑,在httpClient裡面,是連線我們的請求與響應的一箇中間橋樑,所有的請求引數都是通過HttpEntity攜帶過去的
    // 通過client來執行請求,獲取一個響應結果
    CloseableHttpResponse response = client.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String str = EntityUtils.toString(entity, "UTF-8");
    System.out.println(str);
    // 關閉
    response.close();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}