長話短說,廢話不說linux
1、第一種方式,經過HttpClient方式,代碼以下:json
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; }
2、第二種方式,經過流的形式,貼代碼:windows
/** * 發送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
補充:問題找到緣由了,由於公司無論是測試環境機器仍是正式環境機器,訪問公網都是要權限審批的,所以當我去請求樂視時沒有訪問api.letvcloud.com公網的權限,權限開通後,問題解決,一切正常app