長話短說,廢話不說
一、第一種方式,通過HttpClient方式,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
throws HttpException, IOException { String json = null ; HttpGet httpGet = new HttpGet(); // 設置參數 try { httpGet.setURI( new URI(url)); } catch (URISyntaxException e) { } // 發送請求 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; } |
二、第二種方式,通過流的形式,貼代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/** * 發送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卻正常訪問,而且,換另外一臺預發機也能正常獲取數據,目前還沒有研究出個所以然。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。