Filed Under 学习札记 post by GoER / 2012-2-16 20:50 Thursday 出自网络搜索引擎巨头的Android平台,其对网络的支持自然不用多说,在Android SDK中已经集成了Apache的HttpClient模块。使用HttpClient模块,我们就可以使用HTTP协议进行网络连接了。下面则是使用HttpClient中的HttpPost()方法进行http通信的实例:
view sourceprint?01 /**
02 *description:Android HttpPost()
03 *authour:YanEr·Gates
04 *website:http://www.gogogogo.me
05 */
06 package me.gogogoog;
07
08 import java.io.IOException;
09
10 import java.util.ArrayList;
11 import java.util.List;
12 import org.apache.http.HttpEntity;
13 import org.apache.http.HttpResponse;
14 import org.apache.http.HttpStatus;
15 import org.apache.http.NameValuePair;
16 import org.apache.http.client.ClientProtocolException;
17 import org.apache.http.client.HttpClient;
18 import org.apache.http.client.entity.UrlEncodedFormEntity;
19 import org.apache.http.client.methods.HttpPost;
20 import org.apache.http.impl.client.DefaultHttpClient;
21 import org.apache.http.message.BasicNameValuePair;
22 import org.apache.http.util.EntityUtils;
23 import android.app.Activity;
24 import android.widget.TextView;
25
26 public class ResultActivity extends Activity{
27
28 /** Called when the activity is first created. */
29 @Override
30 public void onCreate(Bundle savedInstanceState){
31 super.onCreate(savedInstanceState);
32 setContentView(R.layout.result);
33
34 TextView resultText = (TextView) this.findViewById(R.id.resultText);
35 String username="username";
36 String password="password";
37 String httpUrl = "http://192.168.1.90:8080/AndroidLogin/loginAction.do?method=login";
38
39 //创建httpRequest对象
40 HttpPost httpRequest = new HttpPost(httpUrl);
41
42 List 43 params.add(new BasicNameValuePair("username //HttpStatus.SC_OK表示连接成功 60 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 61 //取得返回的字符串 62 String strResult = EntityUtils.toString(httpResponse.getEntity()); 63 resultText.setText(strResult); }else{ 65 resultText.setText("请求错误!"); 66 } 67 }catch (ClientProtocolException e){ 68 resultText.setText(e.getMessage().toString()); 69 } catch (IOException e){ 70 resultText.setText(e.getMessage().toString()); 71 }catch (Exception e){ 72 resultText.setText(e.getMessage().toString()); 73 } 74 } 75 }下载本文