1. 程式人生 > >java傳送post請求並傳json格式引數

java傳送post請求並傳json格式引數

/**
     * 傳送post請求
     * @param url  路徑
     * @param jsonObject  引數(json型別)
     * @param encoding 編碼格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
        String body = "";

        //建立httpclient物件
        CloseableHttpClient client = HttpClients.createDefault();
        //建立post方式請求物件
        HttpPost httpPost = new HttpPost(url);

        //裝填引數
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //設定引數到請求物件中
        httpPost.setEntity(s);
        System.out.println("請求地址:"+url);
//        System.out.println("請求引數:"+nvps.toString());

        //設定header資訊
        //指定報文頭【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //執行請求操作,並拿到結果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //獲取結果實體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定編碼轉換結果實體為String型別
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //釋放連結
        response.close();
        return body;
    }