Android通過(guò)HttpURLConnection和HttpClient接口實(shí)現(xiàn)網(wǎng)絡(luò)編程
Android中提供的HttpURLConnection和HttpClient接口可以用來(lái)開(kāi)發(fā)HTTP程序。以下是學(xué)習(xí)中的一些經(jīng)驗(yàn)。
1、HttpURLConnection接口
首先需要明確的是,Http通信中的POST和GET請(qǐng)求方式的不同。GET可以獲得靜態(tài)頁(yè)面,也可以把參數(shù)放在URL字符串后面,傳遞給服務(wù)器。而POST方法的參數(shù)是放在Http請(qǐng)求中。因此,在編程之前,應(yīng)當(dāng)首先明確使用的請(qǐng)求方法,然后再根據(jù)所使用的方式選擇相應(yīng)的編程方式。HttpURLConnection是繼承于URLConnection類,二者都是抽象類。其對(duì)象主要通過(guò)URL的openConnection方法獲得。創(chuàng)建方法如下代碼所示:
URL url = new URL("http://www.xxx.com/index.jsp?type=231");
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
通過(guò)以下方法可以對(duì)請(qǐng)求的屬性進(jìn)行一些設(shè)置,如下所示:
//設(shè)置輸入和輸出流
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
//設(shè)置請(qǐng)求方式為POST
urlConn.setRequestMethod("POST");
//POST請(qǐng)求不能使用緩
urlConn.setUseCaches(false);
urlConn.disConnection();
HttpURLConnection默認(rèn)使用GET方式,例如下面代碼所示:
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
while (((inputLine = buffer.readLine()) != null)) {
resultData += inputLine + "\n";
}
in.close();
urlConn.disconnect();
如果需要使用POST方式,則需要setRequestMethod設(shè)置。代碼如下:
String httpUrl = "http://www.xxx.com/getUser.jsp";
String resultData = "";
URL url = null;
try {
url = new URL(httpUrl);
} catch (MalformedURLException e) {
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null) {
try {
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//因?yàn)檫@個(gè)是post請(qǐng)求,設(shè)立需要設(shè)置為true
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("POST"); // 設(shè)置以POST方式
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 這些配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會(huì)隱含的進(jìn)行connect。
urlConn.connect();
// DataOutputStream流
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
String content = "name=" + URLEncoder.encode("張三", "GB2312");
out.writeBytes(content);
out.flush();
out.close();
} catch(Exception e) {
//
}
}
2、HttpClient接口
使用Apache提供的HttpClient接口同樣可以進(jìn)行HTTP操作。對(duì)于GET和POST請(qǐng)求方法的操作有所不同。GET方法的操作代碼示例如下:
String httpUrl = "http://www.xxx.com/getUser.jsp?par=123";
// HttpGet連接對(duì)象
HttpGet httpRequest = new HttpGet(httpUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
// 請(qǐng)求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView.setText(strResult);
} else {
mTextView.setText("請(qǐng)求錯(cuò)誤!");
}
使用POST方法進(jìn)行參數(shù)傳遞時(shí),需要使用NameValuePair來(lái)保存要傳遞的參數(shù)。另外,還需要設(shè)置所使用的字符集。代碼如下所示:
String httpUrl = "http://www.xxx.com/getUser.jsp";
HttpPost httpRequest = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userId", "123"));
HttpEntity httpentity = new UrlEncodedFormEntity(params, "GB2312"); //設(shè)置字符集
httpRequest.setEntity(httpentity);
//取得默認(rèn)的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示連接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView.setText(strResult);
} else {
mTextView.setText("請(qǐng)求錯(cuò)誤!");
}
HttpClient實(shí)際上是對(duì)Java提供方法的一些封裝,在HttpURLConnection中的輸入輸出流操作,在這個(gè)接口中被統(tǒng)一封裝成了HttpPost(HttpGet)和HttpResponse,這樣,就減少了操作的繁瑣性。
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
相關(guān)文章
Android使用android-wheel實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng)
這篇文章主要為大家詳細(xì)介紹了Android使用android-wheel實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08
Android快速實(shí)現(xiàn)無(wú)預(yù)覽拍照功能
這篇文章主要為大家詳細(xì)介紹了Android快速實(shí)現(xiàn)無(wú)預(yù)覽拍照功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
Android 桌面Widget開(kāi)發(fā)要點(diǎn)解析(時(shí)間日期Widget)
總的來(lái)說(shuō),widget主要功能就是顯示一些信息。我們今天編寫(xiě)一個(gè)很簡(jiǎn)單的作為widget,顯示時(shí)間、日期、星期幾等信息。需要顯示時(shí)間信息,那就需要實(shí)時(shí)更新,一秒或者一分鐘更新一次2013-07-07
Android使用BroadcastReceiver監(jiān)聽(tīng)網(wǎng)絡(luò)連接狀態(tài)的改變
這篇文章主要為大家詳細(xì)介紹了Android使用BroadcastReceiver監(jiān)聽(tīng)網(wǎng)絡(luò)連接狀態(tài)的改變,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
Android 藍(lán)牙連接 ESC/POS 熱敏打印機(jī)打印實(shí)例(藍(lán)牙連接篇)
這篇文章主要介紹了Android 藍(lán)牙連接 ESC/POS 熱敏打印機(jī)打印實(shí)例(藍(lán)牙連接篇),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04
基于Android設(shè)計(jì)模式之--SDK源碼之策略模式的詳解
本篇文章介紹了,基于Android設(shè)計(jì)模式之--SDK源碼之策略模式的詳解。需要的朋友參考下2013-04-04
android 使用kotlin 實(shí)現(xiàn)點(diǎn)擊更換全局語(yǔ)言(中日英切換)
這篇文章主要介紹了android kotlin 點(diǎn)擊更換全局語(yǔ)言的實(shí)現(xiàn)方法,這里主要介紹中日英切換,需要的朋友可以參考下2019-11-11

