Androd学习笔记——[转]Android Http get post请求 - lingyun1120
2012-1-10 17:3:0 Author: www.cnblogs.com(查看原文) 阅读量:2 收藏

首先我们先了解下Get请求和Post请求的区别:

表单提交中get和 post方式的区别有5点:
1.get是从服务器上获取数据,post是向服务器传送数据。
2.get是把参数数据队列加到提交表单的 ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
3.对于get方式,服务器端用 Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。
4.get 传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。
5.get安全性非常低,post安全性较高。

一、HttpClinet方式

1、HTTP GET 示例:

 1 public class TestHttpGetMethod{  
2 public void get(){
3 BufferedReader in = null;
4 try{
5 HttpClient client = new DefaultHttpClient();
6 HttpGet request = new HttpGet();
7 request.setURI("http://w26.javaeye.com");
8 HttpResponse response = client.execute(request);
9 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
10 StringBuffer sb = new StringBuffer("");
11 String line = "";
12 String NL = System.getProperty("line.separator");
13 while((line = in.readLine()) != null){
14 sb.append(line + NL);
15
16 }
17 in.close();
18 String page = sb.toString();
19 Log.i(TAG, page);
20 }catch(Exception e){
21 Log.e(TAG,e.toString())
22 }finally{
23 if(in != null){
24 try{
25 in.close();
26 }catch(IOException ioe){
27 Log.e(TAG, ioe.toString());
28 }
29 }
30 }
31 }
32 }


带参数的 HTTP GET:
HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl"); 
client.execute(request);

2、HTTP POST 示例:

 1 public class TestHttpPostMethod{  
2 public void post(){
3 BufferedReader in = null;
4 try{
5 HttpClient client = new DefaultHttpClient();
6 HttpPost request = new HttpPost("http://localhost/upload.jsp");
7 List<NameValuePair> postParams = new ArrayList<NameValuePair>();
8 postParams.add(new BasicNameValuePair("filename", "sex.mov"));
9 UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);
10 request.setEntity(formEntity);
11 HttpResponse response = client.execute(request);
12 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
13 StringBuffer sb = new StringBuffer("");
14 String line = "";
15 String NL = System.getProperty("line.separator");
16 while((line = in.readLine()) != null){
17 sb.append(line + NL);
18 }
19 in.close();
20 String result = sb.toString();
21 Log.i(TAG, result );
22 }catch(Exception e){
23 Log.e(TAG,e.toString())
24 }finally{
25 if(in != null){
26 try{
27 in.close();
28 }catch(IOException ioe){
29 Log.e(TAG, ioe.toString());
30 }
31 }
32 }
33 }
34 }


二、HttpURLConnection 方式

 1 URL url = null;
2 HttpURLConnection conn = null;
3 InputStream in = null;
4 OutputStream out = null;
5 byte[] data ="测试字符串".getBytes();
6 try{
7 url =new URL("www.xxx.com/servlet");
8 conn = (HttpURLConnection) url.openConnection();
9
10 //设置连接属性
11 conn.setDoOutput(true);// 使用 URL 连接进行输出
12 conn.setDoInput(true);// 使用 URL 连接进行输入
13 conn.setUseCaches(false);// 忽略缓存
14 conn.setConnectTimeout(30000);//设置连接超时时长,单位毫秒
15 conn.setRequestMethod("POST");//设置请求方式,POST or GET,注意:如果请求地址为一个servlet地址的话必须设置成POST方式
16
17 //设置请求头
18 conn.setRequestProperty("Accept", "*/*");
19 conn.setRequestProperty("Connection", "Keep-Alive");
20 conn.setRequestProperty("Accept-Charset", "utf-8");
21 if (data != null) {
22 out = conn.getOutputStream();
23 out.write(data);
24 }
25 int code = conn.getResponseCode();
26 if(code ==200){
27 in = conn.getInputStream();// 可能造成阻塞
28 long len = conn.getContentLength();
29 byte[] bs = new byte[(int) len];//返回结果字节数组
30 int all = 0;
31 int dn = 0;
32 while ((dn = in.read(bs, all, 1)) > 0) {
33 all += dn;
34 if (all == len) {
35 break;
36 }
37 }
38 }
39 }

======================================

那么接下来让我们看看在Android平台开发中如何执行一个Post请求:

以下是代码示例:

 1 package com.jixuzou.search;
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.view.View;
15 import android.view.View.OnClickListener;
16 import android.widget.Button;
17 public class mian extends Activity {
18 /** Called when the activity is first created. */
19 private Button btnTest;
20 @Override
21 public void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 setContentView(R.layout.main);
24 btnTest = (Button) findViewById(R.id.Button01);
25 btnTest.setOnClickListener(new OnClickListener() {
26 @Override
27 public void onClick(View v) {
28 getWeather();
29 }
30 });
31 }
32 private void getWeather(){
33 try {
34 final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
35 HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求
36 List params = new ArrayList();
37 params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数
38 params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数
39 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码
40 HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈
41 // 解析返回的内容
42 if (httpResponse.getStatusLine().getStatusCode() != 404)
43 {
44 String result = EntityUtils.toString(httpResponse.getEntity());
45 System.out.println(result);
46 }
47 } catch (Exception e) {
48 }
49 }
50 }

文章来源: https://www.cnblogs.com/lingyun1120/archive/2012/01/10/2318308.html
如有侵权请联系:admin#unsafe.sh