Android應用經常會和伺服器端互動,這就需要手機用戶端發送網路請求,下面介紹四種常用網路請求方式,我這邊是通過Android單元測試來完成這四種方法的,還不清楚Android的單元測試的同學們請看Android開發技巧總結中的Android單元測試的步驟一文。
java.net包中的HttpURLConnection類
Get方式:
// Get方式請求<br />public static void requestByGet() throws Exception {<br />String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";<br />// 建立一個URL對象<br />URL url = new URL(path);<br />// 開啟一個HttpURLConnection串連<br />HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();<br />// 設定連線逾時時間<br />urlConn.setConnectTimeout(5 * 1000);<br />// 開始串連<br />urlConn.connect();<br />// 判斷請求是否成功<br />if (urlConn.getResponseCode() == HTTP_200) {<br />// 擷取返回的資料<br />byte[] data = readStream(urlConn.getInputStream());<br />Log.i(TAG_GET, "Get方式請求成功,返回資料如下:");<br />Log.i(TAG_GET, new String(data, "UTF-8"));<br />} else {<br />Log.i(TAG_GET, "Get方式請求失敗");<br />}<br />// 關閉串連<br />urlConn.disconnect();<br />}
Post方式:
// Post方式請求<br />public static void requestByPost() throws Throwable {<br />String path = "https://reg.163.com/logins.jsp";<br />// 請求的參數轉換為byte數組<br />String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")<br />+ "&pwd=" + URLEncoder.encode("android", "UTF-8");<br />byte[] postData = params.getBytes();<br />// 建立一個URL對象<br />URL url = new URL(path);<br />// 開啟一個HttpURLConnection串連<br />HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();<br />// 設定連線逾時時間<br />urlConn.setConnectTimeout(5 * 1000);<br />// Post請求必須設定允許輸出<br />urlConn.setDoOutput(true);<br />// Post請求不能使用緩衝<br />urlConn.setUseCaches(false);<br />// 設定為Post請求<br />urlConn.setRequestMethod("POST");<br />urlConn.setInstanceFollowRedirects(true);<br />// 配置請求Content-Type<br />urlConn.setRequestProperty("Content-Type",<br />"application/x-www-form-urlencode");<br />// 開始串連<br />urlConn.connect();<br />// 發送請求參數<br />DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());<br />dos.write(postData);<br />dos.flush();<br />dos.close();<br />// 判斷請求是否成功<br />if (urlConn.getResponseCode() == HTTP_200) {<br />// 擷取返回的資料<br />byte[] data = readStream(urlConn.getInputStream());<br />Log.i(TAG_POST, "Post請求方式成功,返回資料如下:");<br />Log.i(TAG_POST, new String(data, "UTF-8"));<br />} else {<br />Log.i(TAG_POST, "Post方式請求失敗");<br />}<br />}
org.apache.http包中的HttpGet和HttpPost類
Get方式:
// HttpGet方式請求<br />public static void requestByHttpGet() throws Exception {<br />String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";<br />// 建立HttpGet對象<br />HttpGet httpGet = new HttpGet(path);<br />// 擷取HttpClient對象<br />HttpClient httpClient = new DefaultHttpClient();<br />// 擷取HttpResponse執行個體<br />HttpResponse httpResp = httpClient.execute(httpGet);<br />// 判斷是夠請求成功<br />if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {<br />// 擷取返回的資料<br />String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");<br />Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回資料如下:");<br />Log.i(TAG_HTTPGET, result);<br />} else {<br />Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");<br />}<br />}
Post方式:
// HttpPost方式請求<br />public static void requestByHttpPost() throws Exception {<br />String path = "https://reg.163.com/logins.jsp";<br />// 建立HttpPost對象<br />HttpPost httpPost = new HttpPost(path);<br />// Post參數<br />List<NameValuePair> params = new ArrayList<NameValuePair>();<br />params.add(new BasicNameValuePair("id", "helloworld"));<br />params.add(new BasicNameValuePair("pwd", "android"));<br />// 設定字元集<br />HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);<br />// 設定參數實體<br />httpPost.setEntity(entity);<br />// 擷取HttpClient對象<br />HttpClient httpClient = new DefaultHttpClient();<br />// 擷取HttpResponse執行個體<br />HttpResponse httpResp = httpClient.execute(httpPost);<br />// 判斷是夠請求成功<br />if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {<br />// 擷取返回的資料<br />String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");<br />Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回資料如下:");<br />Log.i(TAG_HTTPGET, result);<br />} else {<br />Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");<br />}<br />}
以上是一些部分代碼,測試的時候在測試類別中運行對應的測試方法即可。完整代碼點這裡下載