Android发送post请求

  1. android 向web服务器发送post请求并获取结果,因为 需要访问到网络必须要有权限,先在AndroidManifest.xml中加入如下配置:
  2. <uses-permission android:name="android.permission.INTERNET" /> 


  3. package httppost.pack; 
  4.  
  5. import java.util.ArrayList; 
  6. import java.util.List; 
  7.  
  8. import org.apache.http.HttpResponse; 
  9. import org.apache.http.NameValuePair; 
  10. import org.apache.http.client.entity.UrlEncodedFormEntity; 
  11. import org.apache.http.client.methods.HttpPost; 
  12. import org.apache.http.impl.client.DefaultHttpClient; 
  13. import org.apache.http.message.BasicNameValuePair; 
  14. import org.apache.http.protocol.HTTP; 
  15. import org.apache.http.util.EntityUtils; 
  16.  
  17. import android.app.Activity; 
  18. import android.os.Bundle; 
  19. import android.widget.TextView; 
  20.  
  21. public class AndroidHttpPost extends Activity { 
  22.     /** Called when the activity is first created. */ 
  23.     String action="http://www.beijibear.com/android_post.php"
  24.     HttpPost httpRequest=null
  25.     List <NameValuePair> params=null
  26.     HttpResponse httpResponse; 
  27.     TextView tv=null
  28.     @Override 
  29.     public void onCreate(Bundle savedInstanceState) { 
  30.         super.onCreate(savedInstanceState); 
  31.         setContentView(R.layout.main); 
  32.         tv=(TextView)findViewById(R.id.textView1); 
  33.         /*建立HttpPost连接*/ 
  34.         httpRequest=new HttpPost(action); 
  35.         /*Post运作传送变数必须用NameValuePair[]阵列储存*/ 
  36.         params=new ArrayList<NameValuePair>(); 
  37.         params.add(new BasicNameValuePair("username","beijibear")); 
  38.          
  39.         try { 
  40.             //发出HTTP request 
  41.             httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); 
  42.             //取得HTTP response 
  43.             httpResponse=new DefaultHttpClient().execute(httpRequest); 
  44.             //若状态码为200 
  45.             if(httpResponse.getStatusLine().getStatusCode()==200){ 
  46.                 //取出回应字串 
  47.                 String strResult=EntityUtils.toString(httpResponse.getEntity()); 
  48.                 tv.setText(strResult); 
  49.             }else
  50.                 tv.setText("Error Response"+httpResponse.getStatusLine().toString()); 
  51.             } 
  52.         } catch (Exception e) { 
  53.             // TODO Auto-generated catch block 
  54.             tv.setText(e.getMessage().toString()); 
  55.         } 
  56.     } 

原文地址:http://blog.163.com/xiang_zhifang/blog/static/115749500201212945739636/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值