JAVA網絡請求request body(請求參數放在body內傳給服務器)

@SuppressWarnings("deprecation")
    public static String upperPost(String url, String param, String appKey,
            String timesTamp, String signature) {
        String body = "";
        try {
            HttpClient hc = HttpClients.createDefault();
            // Post請求
            HttpPost httppost = new HttpPost(url);
            // 設置參數

            // 設置通用的請求屬性

           //服務器接收數據類型
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("connection", "Keep-Alive");
            httppost.setHeader("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            //接收數據格式
            httppost.setHeader("Accept-Charset", "UTF-8");

           //請求參數類型
            httppost.setHeader("content-type", "application/json;charset=UTF-8");
            // 平臺請求頭,拷貝代碼這部分可以不用
            httppost.setHeader("Aplus-OpenAPI-Version", "1.0.0");
            httppost.setHeader("Aplus-OpenAPI-Access-Key-Id", appKey);
            httppost.setHeader("Aplus-OpenAPI-TimeStamp", timesTamp);
            httppost.setHeader("Aplus-OpenAPI-Signature-Nonce", timesTamp);
            httppost.setHeader("Aplus-OpenAPI-Signature-Version", "1.0");
            httppost.setHeader("Aplus-OpenAPI-Signature", signature);
            /* 設置參數 */
           //關鍵部分傳參數,本文僅介紹穿string類型
            httppost.setEntity(new StringEntity(param, "UTF-8"));
            // 發送請求
            HttpResponse httpresponse = hc.execute(httppost);
            HttpEntity entity = httpresponse.getEntity();
            // 獲取結果實體
            if (entity != null) {// 按指定編碼轉換結果實體爲String類型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            // EntityUtils.consume(entity);
            hc.getConnectionManager().shutdown();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (ParseException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return body;
    }

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