java發(fā)送http get請求的兩種方法(總結)
長話短說,廢話不說
一、第一種方式,通過HttpClient方式,代碼如下:
public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 設置參數(shù) try { httpGet.setURI(new URI(url)); } catch (URISyntaxException e) { throw new HttpException("請求url格式錯誤。"+e.getMessage()); } // 發(fā)送請求 HttpResponse httpResponse = client.execute(httpGet); // 獲取返回的數(shù)據(jù) 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; }
二、第二種方式,通過流的形式,貼代碼:
/** * 發(fā)送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(); } }
這兩種實現(xiàn)方式不同,怎么使用看個人喜好吧,不過我在項目開發(fā)過程中,使用流的方式部署在預發(fā)機(linux機器)上會出現(xiàn)返回null的情況,但是本地windows卻正常訪問,而且,換另外一臺預發(fā)機也能正常獲取數(shù)據(jù),目前還沒有研究出個所以然。。。
以上這篇java發(fā)送http get請求的兩種方法(總結)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
如何解決springboot數(shù)據(jù)庫查詢時出現(xiàn)的時區(qū)差異問題
這篇文章主要介紹了如何解決springboot數(shù)據(jù)庫查詢時出現(xiàn)的時區(qū)差異問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01springboot使用maven實現(xiàn)多環(huán)境運行和打包問題
這篇文章主要介紹了springboot使用maven實現(xiàn)多環(huán)境運行和打包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Java?ConcurrentHashMap實現(xiàn)線程安全的代碼示例
眾所周知ConcurrentHashMap是HashMap的多線程版本,HashMap?在并發(fā)操作時會有各種問題,而這些問題,只要使用ConcurrentHashMap就可以完美解決了,本文將給詳細介紹ConcurrentHashMap是如何保證線程安全的2023-05-05