java發送http get請求的兩種方式


  長話短說,廢話不說

  一、第一種方式,通過HttpClient方式,代碼如下:

public static String httpGet(String url, String charset)
      throws HttpException, IOException {
   String json = null;
   HttpGet httpGet = new HttpGet();
   // 設置參數
   try {
      httpGet.setURI(new URI(url));
   } catch (URISyntaxException e) {
      throw new HttpException("請求url格式錯誤。"+e.getMessage());
   }
   // 發送請求
   HttpResponse httpResponse = client.execute(httpGet);
   // 獲取返回的數據
   HttpEntity entity = httpResponse.getEntity();
   byte[] body = EntityUtils.toByteArray(entity);
   StatusLine sL = httpResponse.getStatusLine();
   int statusCode = sL.getStatusCode();
   if (statusCode == 200) {
      json = new String(body, charset);
      entity.consumeContent();
   } else {
      throw new HttpException("statusCode="+statusCode);
   }
   return json;
}

 

  二、第二種方式,通過流的形式,貼代碼:

  

    /**
    * 發送http get請求
    * 
    * @param getUrl
    * @return
    */
   public String sendGetRequest(String getUrl)
   {
      StringBuffer sb = new StringBuffer();
      InputStreamReader isr = null;
      BufferedReader br = null;
      try
      {
         URL url = new URL(getUrl);
         URLConnection urlConnection = url.openConnection();
         urlConnection.setAllowUserInteraction(false);
         isr = new InputStreamReader(url.openStream());
         br = new BufferedReader(isr);
         String line;
         while ((line = br.readLine()) != null)
         {
            sb.append(line);
         }
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
      finally
      {
         fileOperator.closeResources(isr, br);
      }
      return sb.toString();
   }
}

  這兩種實現方式不同,怎么使用看個人喜好吧,不過我在項目開發過程中,使用流的方式部署在預發機(linux機器)上會出現發送請求返回null的情況,但是本地windows卻正常訪問,而且,換另外一台預發機也能正常獲取數據,目前還沒有研究出個所以然。。。

 

補充:問題找到原因了,因為公司不管是測試環境機器還是正式環境機器,訪問公網都是要權限審批的,因此當我去請求樂視時沒有訪問api.letvcloud.com公網的權限,權限開通后,問題解決,一切正常

  

  

 


免責聲明!

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



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