Android发送post请求

本文介绍了如何在Android应用中发送POST请求。通过创建HttpPost对象,设置请求地址,并使用NameValuePair列表传递参数,如username和password。然后使用DefaultHttpClient执行请求并检查响应状态,当状态码为200时,表示请求成功。
public class TestSendDataActivity extends Activity {
        //请求地址的连接
        String action="http://192.168.1.109:8088/EABox";
        //发送post连接
        HttpPost httpRequest=null;
        //用来传递参数
        List <NameValuePair> params=null;
        //接收响应
        HttpResponse httpResponse;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            //建立HttpPost连接
            httpRequest=new HttpPost(action);
            //Post运作传送变数必须用NameValuePair[]阵列储存
            params=new ArrayList<NameValuePair>();
            //传递参数username是传递的自动,kobe要传递的值
            params.add(new BasicNameValuePair("username","kobe"));
            params.add(new BasicNameValuePair("password","12345"));
            try {
                //发出HTTP request
                httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
                //httpRequest.setEntity(new StringEntity(params.toString()));
                //取得HTTP response
                httpResponse=new DefaultHttpClient().execute(httpRequest);
                Log.i("tag", "得到返回状态是:"+httpResponse.getStatusLine().getStatusCode());
                //若状态码为200
                if(httpResponse.getStatusLine().getStatusCode()==200){
                    //取出回应字串
                    String strResult=EntityUtils.toString(httpResponse.getEntity());
                }else{
                     Log.i("tag", "没发送成功");
                }
            } catch (Exception e) {
                
                 Log.i("tag", "报错了"+e.getMessage().toString());
            }
        }
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值