【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 1322|回复: 0

Android发送post请求

[复制链接]
发表于 2013-1-15 22:21:09 | 显示全部楼层 |阅读模式
android 向web服务器发送post请求并获取结果,因为 需要访问到网络必须要有权限,先在AndroidManifest.xml中加入如下配置:
  1. <uses-permission  android:name="android.permission.INTERNET"/>
复制代码
  1. package httppost.pack;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.message.BasicNameValuePair;
  10. import org.apache.http.protocol.HTTP;
  11. import org.apache.http.util.EntityUtils;

  12. import android.app.Activity;
  13. import android.os.Bundle;
  14. import android.widget.TextView;
  15. public class AndroidHttpPost extends Activity {
  16.      /** Called when the activity is first created. */
  17.      String action="http://www.beijibear.com/android_post.php";
  18.      HttpPost httpRequest=null;
  19.      List <NameValuePair> params=null;
  20.      HttpResponse httpResponse;
  21.      TextView tv=null;
  22. @Override
  23. public void onCreate(Bundle savedInstanceState) {
  24.      super.onCreate(savedInstanceState);
  25.      setContentView(R.layout.main);
  26.      tv=(TextView)findViewById(R.id.textView1);
  27.      /*建立HttpPost连接*/
  28.      httpRequest=new HttpPost(action);
  29.      /*Post运作传送变数必须用NameValuePair[]阵列储存*/
  30.      params=new ArrayList<NameValuePair>();
  31.      params.add(new BasicNameValuePair("username","beijibear"));
  32. try {
  33.      //发出HTTP request
  34.       httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
  35.      //取得HTTP response
  36.      httpResponse=new DefaultHttpClient().execute(httpRequest);
  37.      //若状态码为200
  38.      if(httpResponse.getStatusLine().getStatusCode()==200){
  39.      //取出回应字串
  40.      String strResult=EntityUtils.toString(httpResponse.getEntity());
  41.       tv.setText(strResult);
  42.      }else{
  43.      tv.setText("Error Response"+httpResponse.getStatusLine().toString());
  44. }
  45. } catch (Exception e) {
  46.      // TODO Auto-generated catch block
  47.      tv.setText(e.getMessage().toString());
  48.     }
  49.   }
  50. }
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-9-29 05:17

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表