發送HTTP_GET請求 表頭application/json


/**
     * 發送HTTP_GET請求
     * 該方法會自動關閉連接,釋放資源
     * @param reqURL    請求地址(含參數)
     * @param decodeCharset 解碼字符集,解析響應數據時用之,其為null時默認采用UTF-8解碼
     * @return 遠程主機響應正文
     */
    public static String sendGetRequest(String reqURL,Map<String, String> paramMap, String decodeCharset){
        long responseLength = 0;       //響應長度
        String responseContent = null; //響應內容
        HttpClient httpClient = new DefaultHttpClient(); //創建默認的httpClient實例
        if (!paramMap.isEmpty()) {
            for (String key : paramMap.keySet()) {
                if (reqURL.indexOf('?') == -1) {
                    reqURL += "?" + key+"="+paramMap.get(key);
                } else {
                    reqURL += "&" + key+"="+paramMap.get(key);
                }
            }

        }
        HttpGet httpGet = new HttpGet(reqURL);           //創建org.apache.http.client.methods.HttpGet
        try{
            HttpResponse response = httpClient.execute(httpGet); //執行GET請求
            response.setHeader("Content-Type","application/json");
            HttpEntity entity = response.getEntity();            //獲取響應實體
            if(null != entity){
                responseLength = entity.getContentLength();
                responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity); //Consume response content
            }
            System.out.println("請求地址: " + httpGet.getURI());
            System.out.println("響應狀態: " + response.getStatusLine());
            System.out.println("響應長度: " + responseLength);
            System.out.println("響應內容: " + responseContent);
        }catch(ClientProtocolException e){
            logger.debug("該異常通常是協議錯誤導致,比如構造HttpGet對象時傳入的協議不對(將'http'寫成'htp')或者服務器端返回的內容不符合HTTP協議要求等,堆棧信息如下", e);
        }catch(ParseException e){
            logger.debug(e.getMessage(), e);
        }catch(IOException e){
            logger.debug("該異常通常是網絡原因引起的,如HTTP服務器未啟動等,堆棧信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown(); //關閉連接,釋放資源
        }
        return responseContent;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM