/** * 發送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; }