android http post和get,Android用Apache HttpClient 实现POST和Get请求

快速记忆(POST)

1.       要想连接网络,肯定需要一个客户端对象,所以首先创建一个客户端对象HttpClient

2.       拥有客户端对象之后肯定需要对互联网进行访问,首先要对互联网进行请求,所以要创建一个请求对象HttpUriRequest,因为是Post请求,所以使用HttpPost

3.       我们知道请求对象包含请求行(方法、路径、协议),消息头,请求实体三部分。通过new HttpPost(uri)可以设置请求行的路径,现在需要设置请求实体中的请求参数。

我们知道请求参数一定是由请求参数的名称和请求参数的值组成。这时就需要一个类NameValuePair,这是一个键值对,在初始化的时候为了简便直接使用其子类BaseNameValuePair(String name , String value)。

如果有多组请求参数就要使用List集合List

4.       已经有一个存放参数的键值对的集合只有,就可以创建一个请求实体对象,并且将参数集合传进去—new UrlDecodedFormEntity(List)

5.       然后设置请求对象的请求实体

request.setEntity(new UrlDecodedFormEntity(List))

6.       现在不管是要访问的网络地址还是参数就都已经放入请求对象中了,现在就可以利用客户端进行请求—将请求对象发送出去,并且获得响应对象

响应对象  =  客户端对象.execute(请求对象)

7.       我们都知道响应对象也是由状态行(协议,状态码,状态描述),消息头,响应实体三部分组成。现在有了响应对象就可以获取响应对象中的消息。

具体方法见上。

1.  GET实现    (提交网址为:url?参数  的形式,提交的参数值显式地显示在提交的网址中,参数大小是有限制的,安全性也不高)

packagecom.yarin.android.Examples_08_02;

importjava.io.IOException;

importorg.apache.http.HttpResponse;

importorg.apache.http.HttpStatus;

importorg.apache.http.client.ClientProtocolException;

importorg.apache.http.client.HttpClient;

importorg.apache.http.client.methods.HttpGet;

importorg.apache.http.impl.client.DefaultHttpClient;

importorg.apache.http.util.EntityUtils;

importandroid.app.Activity;

importandroid.content.Intent;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.TextView;

publicclassActivity2extendsActivity

{

@Override

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.http);

TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);

// http地址

StringhttpUrl="http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";

// HttpGet连接对象

HttpGethttpRequest=newHttpGet(httpUrl);

try

{

// 取得HttpClient对象

HttpClienthttpclient=newDefaultHttpClient();

// 请求HttpClient,取得HttpResponse

HttpResponsehttpResponse=httpclient.execute(httpRequest);

// 请求成功

if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)

{

// 取得返回的字符串

StringstrResult=EntityUtils.toString(httpResponse.getEntity());

mTextView.setText(strResult);}

else

{

mTextView.setText("请求错误!");

}

}

catch(ClientProtocolExceptione)

{

mTextView.setText(e.getMessage().toString());

}

catch(IOExceptione)

{

mTextView.setText(e.getMessage().toString());

}

catch(Exceptione)

{

mTextView.setText(e.getMessage().toString());

}

// 设置按键事件监听

Buttonbutton_Back=(Button)findViewById(R.id.Button_Back);

/* 监听button的事件信息 */

button_Back.setOnClickListener(newButton.OnClickListener(){

publicvoidonClick(Viewv){

/* 新建一个Intent对象 */

Intentintent=newIntent();/* 指定intent要启动的类 */

intent.setClass(Activity02.this,Activity01.class);

/* 启动一个新的Activity */

startActivity(intent);

/* 关闭当前的Activity */

Activity2.this.finish();

}

});

}

}

2.  POST(参数在请求头中,大小也没有限制,相对于GET请求更安全)

packagecom.yarin.android.Examples_08_02;

importjava.io.IOException;

importjava.util.ArrayList;

importjava.util.List;

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpResponse;

importorg.apache.http.HttpStatus;

importorg.apache.http.NameValuePair;

importorg.apache.http.client.ClientProtocolException;

importorg.apache.http.client.HttpClient;

importorg.apache.http.client.entity.UrlEncodedFormEntity;

importorg.apache.http.client.methods.HttpPost;

importorg.apache.http.impl.client.DefaultHttpClient;

importorg.apache.http.message.BasicNameValuePair;

importorg.apache.http.util.EntityUtils;

importandroid.app.Activity;

importandroid.content.Intent;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.TextView;

publicclassActivity03extendsActivity

{

@Override

publicvoidonCreate(BundlesavedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.http);

TextViewmTextView=(TextView)this.findViewById(R.id.TextView_HTTP);

// http地址

StringhttpUrl="http://192.168.1.110:8080/httpget.jsp";

/*

* NameValuePair代表一个HEADER,List存储全部的头字段

* UrlEncodedFormEntity类似于URLEncoder语句进行URL编码

* HttpPost类似于HTTP的POST请求

* client.execute()类似于发出请求,并返回Response

*/

// HttpPost连接对象

HttpPosthttpRequest=newHttpPost(httpUrl);// 使用NameValuePair来保存要传递的Post参数

Listparams=newArrayList();

// 添加要传递的参数

NameValuePair pair1 = new BasicNameValuePair("par", "HttpClient_android_Post"));

params.add(pair1);

//params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));

try

{

// 设置字符集HttpEntityhttpentity=newUrlEncodedFormEntity(params,"gb2312");

// 请求httpRequest

httpRequest.setEntity(httpentity);

// 取得默认的HttpClient

HttpClienthttpclient=newDefaultHttpClient();

// 取得HttpResponse

HttpResponsehttpResponse=httpclient.execute(httpRequest);

// HttpStatus.SC_OK表示连接成功

if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)

{

// 取得返回的字符串

StringstrResult=EntityUtils.toString(httpResponse.getEntity());

mTextView.setText(strResult);

}

else

{

mTextView.setText("请求错误!");

}

}

catch(ClientProtocolExceptione)

{

mTextView.setText(e.getMessage().toString());

}

catch(IOExceptione)

{

mTextView.setText(e.getMessage().toString());

}

catch(Exceptione)

{

mTextView.setText(e.getMessage().toString());

}// 设置按键事件监听

Buttonbutton_Back=(Button)findViewById(R.id.Button_Back);

/* 监听button的事件信息 */

button_Back.setOnClickListener(newButton.OnClickListener()

{

publicvoidonClick(Viewv)

{

/* 新建一个Intent对象 */

Intentintent=newIntent();

/* 指定intent要启动的类 */

intent.setClass(Activity03.this,Activity01.class);

/* 启动一个新的Activity */

startActivity(intent);

/* 关闭当前的Activity */

Activity03.this.finish();

}

});

}

}

二、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 }

原文:http://my.oschina.net/u/1463230/blog/307317

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值