日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > Android >内容正文

Android

精通Android3笔记--第十一章

發(fā)布時間:2024/4/14 Android 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 精通Android3笔记--第十一章 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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)該作為一個獨立的類來使用它。

2、用Get方法傳遞參數(shù),URL的長度應(yīng)該控制在2048個字符以內(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)的項目

? ? ????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é)議異常如身份驗證錯誤,無效的cookie等。例如,如果必須在HTTP請求中提供登錄憑證但未成功,則可能看到協(xié)議異常。對于HTTP調(diào)用,超時包含兩個方面:連接超時和套接字超時,其中套接字超時為HttpClient可以連接到服務(wù)器,但是在規(guī)定時間內(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("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、在實際應(yīng)用中,應(yīng)該為整個應(yīng)用程序創(chuàng)建一個HttpClient,并將其用于所有HTTP通信。此時就要考慮同時發(fā)出多個請求的多線程問題,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)處理完某個事件,將觸發(fā)ANR(應(yīng)用程序未響應(yīng))條件,影響用戶體驗。如果用戶只是希望簡單計算,無需更新用戶界面,則可以使用簡單的Thread對象來從主線程轉(zhuǎn)移一些處理工作,但是此技術(shù)不適用于對用戶界面施行更新,因為Android用戶界面工具包不是線程安全的,所以它應(yīng)該始終只從主線程更新。如果希望從后臺線程以任何方式更新用戶界面,應(yīng)該認(rèn)真考慮使用AsyncTask。AsyncTask負(fù)責(zé)創(chuàng)建一個后臺線程來完成工作,提供將在主線程上運(yùn)行的回調(diào)函數(shù)來實現(xiàn)對用戶界面元素的訪問。回調(diào)可在后臺線程運(yùn)行之前、期間、之后觸發(fā)。 11、

轉(zhuǎn)載于:https://blog.51cto.com/38275/729496

總結(jié)

以上是生活随笔為你收集整理的精通Android3笔记--第十一章的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。