精通android2_精通Android3筆記
本文關(guān)鍵詞:精通Android3,由筆耕文化傳播整理發(fā)布。
博主的更多文章>>
精通Android3筆記--第十一章
2011-11-30 09:12:28標(biāo)簽:
1、Android附帶了Apache的HttpClient用于HTTP交互。
2、HttpClient Get程序
public class HttpGetDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
HttpClient不附加到activity上,并且應(yīng)該作為一個(gè)獨(dú)立的類來使用它。
2、用Get方法傳遞參數(shù),URL的長度應(yīng)該控制在2048個(gè)字符以內(nèi)
HttpGet request = new HttpGet("?one=valueGoesHere");
client.execute(request);
3、Post方法
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("first","param value one"));
postParameters.add(new BasicNameValuePair("issuenum", "10317"));
postParameters.add(new BasicNameValuePair("username", "dave"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
4、多部分POST,Android本身不支持,可以下載以下jar包
以下網(wǎng)站也有相應(yīng)的項(xiàng)目
Commons IO:
Mime4j:
HttpMime: (inside of HttpClient)
多部分POST代碼:
public void executeMultipartPost() throws Exception {
try {
InputStream is = this.getAssets().open("data.xml");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(
new ByteArrayInputStream(data), "uploadedFile");
StringBody sb1 = new StringBody("some text goes here");
StringBody sb2 = new StringBody("some text goes here too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
response.getEntity().getContent().close();
} catch (Throwable e) {
// handle exception here
}
}
5、Android本身不支持SOAP,可從以下網(wǎng)站尋找相關(guān)資源:
6、Android支持JSON
7、HTTP中可能發(fā)生的異常:網(wǎng)絡(luò)連接異常,協(xié)議異常如身份驗(yàn)證錯(cuò)誤,無效的cookie等。例如,如果必須在HTTP請求中提供登錄憑證但未成功,則可能看到協(xié)議異常。對于HTTP調(diào)用,超時(shí)包含兩個(gè)方面:連接超時(shí)和套接字超時(shí),其中套接字超時(shí)為HttpClient可以連接到服務(wù)器,,但是在規(guī)定時(shí)間內(nèi)未接收到響應(yīng)。
8、HttpClient簡單的重試代碼:
public class TestHttpGet {
public String executeHttpGetWithRetry() throws Exception {
int retry = 3;
int count = 0;
while (count < retry) {
count += 1;
try {
String response = executeHttpGet();
/**
* if we get here, that means we were successful and we can
* stop.
*/
return response;
} catch (Exception e) {
/**
* if we have exhausted our retry limit
*/
if (count < retry) {
/**
* we have retries remaining, so log the message and go
* again.
*/
System.out.println(e.getMessage());
} else {
System.out.println("all retries failed");
throw e;
}
}
}
return null;
}
public String executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
9、在實(shí)際應(yīng)用中,應(yīng)該為整個(gè)應(yīng)用程序創(chuàng)建一個(gè)HttpClient,并將其用于所有HTTP通信。此時(shí)就要考慮同時(shí)發(fā)出多個(gè)請求的多線程問題,Android中已經(jīng)有了相關(guān)方法,即使用ThreadSafeClientConnManager創(chuàng)建DefaultHttpClient:
public class CustomHttpClient {
private static HttpClient customHttpClient;
/** A private Constructor prevents instantiation */
private CustomHttpClient() {
}
public static synchronized HttpClient getHttpClient() {
if (customHttpClient == null) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params,
"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1
(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
);
ConnManagerParams.setTimeout(params, 1000);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 10000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new
ThreadSafeClientConnManager(params,schReg);
customHttpClient = new DefaultHttpClient(conMgr, params);
}
return customHttpClient;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
10、AsyncTask:如果主線程沒有在5秒內(nèi)處理完某個(gè)事件,將觸發(fā)ANR(應(yīng)用程序未響應(yīng))條件,影響用戶體驗(yàn)。如果用戶只是希望簡單計(jì)算,無需更新用戶界面,則可以使用簡單的Thread對象來從主線程轉(zhuǎn)移一些處理工作,但是此技術(shù)不適用于對用戶界面施行更新,因?yàn)锳ndroid用戶界面工具包不是線程安全的,所以它應(yīng)該始終只從主線程更新。如果希望從后臺線程以任何方式更新用戶界面,應(yīng)該認(rèn)真考慮使用AsyncTask。AsyncTask負(fù)責(zé)創(chuàng)建一個(gè)后臺線程來完成工作,提供將在主線程上運(yùn)行的回調(diào)函數(shù)來實(shí)現(xiàn)對用戶界面元素的訪問;卣{(diào)可在后臺線程運(yùn)行之前、期間、之后觸發(fā)。
11、
0人
了這篇文章類別:未分類┆閱讀(0)┆評論(0) ┆ 返回博主首頁┆返回博客首頁
上一篇 精通Android筆記--第六章
職位推薦
文章評論
本文關(guān)鍵詞:精通Android3,由筆耕文化傳播整理發(fā)布。
本文編號:146788
本文鏈接:http://sikaile.net/wenshubaike/mishujinen/146788.html