精通Android3笔记--第十一章
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("http://code.google.com/android/");
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的長(zhǎng)度應(yīng)該控制在2048個(gè)字符以內(nèi)
? ? ??HttpGet request = new HttpGet("http://somehost/WS2/Upload.aspx?one=valueGoesHere");
? ? ? client.execute(request);
3、Post方法
? ? ??HttpClient client = new DefaultHttpClient();
? ? ??HttpPost request = new HttpPost("http://192.165.13.37/services/doSomething.do");
? ? ??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包
? ? ??http://www.apress.com/book/view/1430226595
? ? ? 以下網(wǎng)站也有相應(yīng)的項(xiàng)目
? ? ????Commons IO: http://commons.apache.org/io/
? ? ? ? Mime4j: http://james.apache.org/mime4j/
? ? ? ? HttpMime: http://hc.apache.org/downloads.cgi (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(
"http://mysomewebserver.com/services/doSomething.do");
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)資源:
? ? ??http://ksoap2.sourceforge.net/
? ? ? http://code.google.com/p/ksoap2-android/
6、Android支持JSON
7、HTTP中可能發(fā)生的異常:網(wǎng)絡(luò)連接異常,協(xié)議異常如身份驗(yàn)證錯(cuò)誤,無效的cookie等。例如,如果必須在HTTP請(qǐng)求中提供登錄憑證但未成功,則可能看到協(xié)議異常。對(duì)于HTTP調(diào)用,超時(shí)包含兩個(gè)方面:連接超時(shí)和套接字超時(shí),其中套接字超時(shí)為HttpClient可以連接到服務(wù)器,但是在規(guī)定時(shí)間內(nèi)未接收到響應(yīng)。
8、HttpClient簡(jiǎn)單的重試代碼:
? ? ??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("http://code.google.com/android/");
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è)請(qǐng)求的多線程問題,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)。如果用戶只是希望簡(jiǎn)單計(jì)算,無需更新用戶界面,則可以使用簡(jiǎn)單的Thread對(duì)象來從主線程轉(zhuǎn)移一些處理工作,但是此技術(shù)不適用于對(duì)用戶界面施行更新,因?yàn)锳ndroid用戶界面工具包不是線程安全的,所以它應(yīng)該始終只從主線程更新。如果希望從后臺(tái)線程以任何方式更新用戶界面,應(yīng)該認(rèn)真考慮使用AsyncTask。AsyncTask負(fù)責(zé)創(chuàng)建一個(gè)后臺(tái)線程來完成工作,提供將在主線程上運(yùn)行的回調(diào)函數(shù)來實(shí)現(xiàn)對(duì)用戶界面元素的訪問。回調(diào)可在后臺(tái)線程運(yùn)行之前、期間、之后觸發(fā)。 11、轉(zhuǎn)載于:https://blog.51cto.com/38275/729496
總結(jié)
以上是生活随笔為你收集整理的精通Android3笔记--第十一章的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UVA 10154 Weights an
- 下一篇: 性能测试, 压力测试 , 负载测试和 容