標籤:
1、Android 上發送HTTP 要求的方式一般有兩種,HttpURLConnection 和 HttpClient;
2、HttpURLConnection 的用法:
1)擷取 HttpURLConnection 執行個體:通過調用 URL 對象的 openConnection() 方法擷取;
2)設定 HTTP 要求所使用的方法,常用的有兩個方法: GET 和 POST;
3)其他設定,比如設定連線逾時、讀取逾時的毫秒數等;
connection.setConnectTimeout(8000);connection.setReadTimeout(8000);
4)調用 HttpURLConnection 的 getInputStream() 方法可以擷取到伺服器返回的輸入資料流,通過這個輸入資料流就可以讀取到服務端資料;
5)最後需要調用 disconnect() 方法來關閉串連。
6)範例程式碼:
private String sendRequestWithHttpURLConnection(){ String result = null; HttpURLConnection connection = null; try{ URL url = new URL("http://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream inputStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder sb = new StringBuilder(); String str; while((str = br.readLine()) != null){ sb.append(str); } result = sb.toString(); }catch (Exception e){ e.printStackTrace(); }finally{ if(connection != null){ connection.disconnect(); } } return result;}
3、HttpClient 的用法:
1)HttpClient 是一個介面,通常情況下會建立一個 DefaultHttpClient 的執行個體:HttpClient httpClient = new DefaultHttpClient();
2)佈建要求:
--GET 請求:建立一個 HttpGet 對象,並傳入目標的網路地址,然後調用 HttpClient 的 execute() 方法即可;
--POST請求:建立一個 HttpPost 對象,並傳入目標的網路地址;建立一個 NameValuePair 集合來存放待提交的參數,並將這個參數集合傳入到一個UrlEncodedFormEntity 中,然後調用 HttpPost 的 setEntity() 方法將構建好的 UrlEncodedFormEntity傳入:
List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("username", "admin"));params.add(new BasicNameValuePair("password", "123456"));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");httpPost.setEntity(entity);
3)調用 HttpClient 的 execute() 方法發起請求;
4)執行 execute() 方法之後會返回一個 HttpResponse,物件服務器所返回的所有資訊就會包含在這裡面,通常情況先取出伺服器返回的狀態代碼,如果等於200 就說明請求和響應都成功了,此時可以調用 getEntity() 方法擷取到一個HttpEntity 執行個體,然後再用 EntityUtils.toString() 這個靜態方法將 HttpEntity 轉換成字串;
5)範例程式碼:
private String sendRequestWithHttpClient(String name, String pwd){ String result = null; HttpClient httpClient = null; try { httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.baidu.com"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("pwd", pwd)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); if(response.getStatusLine().getStatusCode() == 200){ HttpEntity entity1 = response.getEntity(); result = EntityUtils.toString(entity1, "UTF-8"); } }catch (Exception e){ e.printStackTrace(); } return result;}
Android--網路請求