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


发送post请求并获取结果的activity 代码如下:
package httppost.pack;  import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class AndroidHttpPost extends Activity {     /** Called when the activity is first created. */     String action="http://www.beijibear.com/android_post.php";          HttpPost httpRequest=null;     List <NameValuePair> params=null;     HttpResponse httpResponse;     TextView tv=null;     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         tv=(TextView)findViewById(R.id.textView1);         /*建立HttpPost连接*/         httpRequest=new HttpPost(action);         /*Post运作传送变数必须用NameValuePair[]阵列储存*/           params=new ArrayList<NameValuePair>();         params.add(new BasicNameValuePair("username","beijibear"));         try {                         //发出HTTP request              httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));             //取得HTTP response             httpResponse=new DefaultHttpClient().execute(httpRequest);                          //若状态码为200             if(httpResponse.getStatusLine().getStatusCode()==200)       {                               //取出回应字串                     String strResult=EntityUtils.toString(httpResponse.getEntity());                 tv.setText(strResult);             }else{                 tv.setText("Error Response"+httpResponse.getStatusLine().toString());             }         } catch (Exception e) {             // TODO Auto-generated catch block             tv.setText(e.getMessage().toString());         }     } } 

更多相关文章

  1. 将大型阵列传输到客户端
  2. 如何在2D阵列中找到局部最小值?
  3. 转发可变数量的参数以通过椭圆运算符接受可变数量的参数

随机推荐

  1. php中.=什么意思
  2. THINKPHP6 多应用隐藏入口文件
  3. php实现记事本案例
  4. Hexo博客框架—轻量、一令部署
  5. php使用event扩展的io复用测试的示例
  6. php redis setnx分布式锁简单原理解析
  7. PHP如何通过带尾指针的链表实现'队列'
  8. 数据库学习小结
  9. CURD 操作,PDO 本质\原理,使用预处理的
  10. JetBrains激活码 | 2022 JetBrains系列ID