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上,并且应该作为一个独立的类来使用它。

2、用Get方法传递参数,URL的长度应该控制在2048个字符以内

      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

      以下网站也有相应的项目

      􀀁 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,可从以下网站寻找相关资源:

      http://ksoap2.sourceforge.net/

      http://code.google.com/p/ksoap2-android/

6、Android支持JSON

7、HTTP中可能发生的异常:网络连接异常,协议异常如身份验证错误,无效的cookie等。例如,如果必须在HTTP请求中提供登录凭证但未成功,则可能看到协议异常。对于HTTP调用,超时包含两个方面:连接超时和套接字超时,其中套接字超时为HttpClient可以连接到服务器,但是在规定时间内未接收到响应。

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、在实际应用中,应该为整个应用程序创建一个HttpClient,并将其用于所有HTTP通信。此时就要考虑同时发出多个请求的多线程问题,Android中已经有了相关方法,即使用ThreadSafeClientConnManager创建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秒内处理完某个事件,将触发ANR(应用程序未响应)条件,影响用户体验。如果用户只是希望简单计算,无需更新用户界面,则可以使用简单的Thread对象来从主线程转移一些处理工作,但是此技术不适用于对用户界面施行更新,因为Android用户界面工具包不是线程安全的,所以它应该始终只从主线程更新。如果希望从后台线程以任何方式更新用户界面,应该认真考虑使用AsyncTask。AsyncTask负责创建一个后台线程来完成工作,提供将在主线程上运行的回调函数来实现对用户界面元素的访问。回调可在后台线程运行之前、期间、之后触发。
11、