你好,游客 登录 注册 搜索
背景:
阅读新闻

Android入门:用HttpClient模拟HTTP的GET和POST请求

[日期:2012-07-22] 来源:Linux社区  作者:xiazdong [字体:大 中 小]

三、Android客户端代码

效果如下:

在AndroidManifest.xml加入:

<uses-permission android:name="android.permission.INTERNET"/>    

MainActivity.java

  1. package org.xiazdong.network.httpclient;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.URLEncoder;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.http.HttpResponse;  
  11. import org.apache.http.NameValuePair;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.client.methods.HttpPost;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.message.BasicNameValuePair;  
  17.   
  18. import android.app.Activity;  
  19. import android.os.Bundle;  
  20. import android.view.View;  
  21. import android.view.View.OnClickListener;  
  22. import android.widget.Button;  
  23. import android.widget.EditText;  
  24. import android.widget.Toast;  
  25.   
  26. public class MainActivity extends Activity {  
  27.     private EditText name, age;  
  28.     private Button getbutton, postbutton;  
  29.     private OnClickListener listener = new OnClickListener() {  
  30.         @Override  
  31.         public void onClick(View v) {  
  32.             try{  
  33.                 if(postbutton==v){  
  34.                     /* 
  35.                      * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段 
  36.                      * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码 
  37.                      * HttpPost类似于HTTP的POST请求 
  38.                      * client.execute()类似于发出请求,并返回Response 
  39.                      */  
  40.                     DefaultHttpClient client = new DefaultHttpClient();  
  41.                     List<NameValuePair> list = new ArrayList<NameValuePair>();  
  42.                     NameValuePair pair1 = new BasicNameValuePair("name", name.getText().toString());  
  43.                     NameValuePair pair2 = new BasicNameValuePair("age", age.getText().toString());  
  44.                     list.add(pair1);  
  45.                     list.add(pair2);  
  46.                     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
  47.                     HttpPost post = new HttpPost("http://192.168.0.103:8080/Server/Servlet1");  
  48.                     post.setEntity(entity);  
  49.                     HttpResponse response = client.execute(post);  
  50.                       
  51.                     if(response.getStatusLine().getStatusCode()==200){  
  52.                         InputStream in = response.getEntity().getContent();//接收服务器的数据,并在Toast上显示   
  53.                         String str = readString(in);  
  54.                         Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();  
  55.                           
  56.                           
  57.                     }  
  58.                     else Toast.makeText(MainActivity.this, "POST提交失败", Toast.LENGTH_SHORT).show();  
  59.                 }  
  60.                 if(getbutton==v){  
  61.                     DefaultHttpClient client = new DefaultHttpClient();  
  62.                     StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/Servlet1");  
  63.                     buf.append("?");  
  64.                     buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");  
  65.                     buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));  
  66.                     HttpGet get = new HttpGet(buf.toString());  
  67.                     HttpResponse response = client.execute(get);  
  68.                     if(response.getStatusLine().getStatusCode()==200){  
  69.                         InputStream in = response.getEntity().getContent();  
  70.                         String str = readString(in);  
  71.                         Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();  
  72.                     }  
  73.                     else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show();  
  74.                 }  
  75.             }  
  76.             catch(Exception e){}  
  77.         }  
  78.     };  
  79.     @Override  
  80.     public void onCreate(Bundle savedInstanceState) {  
  81.         super.onCreate(savedInstanceState);  
  82.         setContentView(R.layout.main);  
  83.         name = (EditText) this.findViewById(R.id.name);  
  84.         age = (EditText) this.findViewById(R.id.age);  
  85.         getbutton = (Button) this.findViewById(R.id.getbutton);  
  86.         postbutton = (Button) this.findViewById(R.id.postbutton);  
  87.         getbutton.setOnClickListener(listener);  
  88.         postbutton.setOnClickListener(listener);  
  89.     }  
  90.     protected String readString(InputStream in) throws Exception {  
  91.         byte[]data = new byte[1024];  
  92.         int length = 0;  
  93.         ByteArrayOutputStream bout = new ByteArrayOutputStream();  
  94.         while((length=in.read(data))!=-1){  
  95.             bout.write(data,0,length);  
  96.         }  
  97.         return new String(bout.toByteArray(),"UTF-8");  
  98.           
  99.     }  
  100. }  
linux
相关资讯       Android入门教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款