转载地址:http://blog.csdn.net/liuhe688/article/details/6425225
在Android中,除了使用java.net包下的API访问HTTP服务之外,我们还可以换一种途径去完成工作。Android SDK附带了Apache的HttpClient API。Apache HttpClient是一个完善的HTTP客户端,它提供了对HTTP协议的全面支持,可以使用HTTP GET和POST进行访问。下面我们就结合实例,介绍一下HttpClient的使用方法。
- package com.scot.http.test;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import junit.framework.Assert;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.mime.MultipartEntity;
- import org.apache.http.entity.mime.content.InputStreamBody;
- import org.apache.http.entity.mime.content.StringBody;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import android.test.AndroidTestCase;
- public class HttpTest extends AndroidTestCase {
- private static final String PATH = "http://192.168.1.57:8080/web";
- public void testGet() throws Exception {
- HttpClient client = new DefaultHttpClient();
- HttpGet get = new HttpGet(PATH + "/TestServlet?id=1001&name=john&age=60");
- HttpResponse response = client.execute(get);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- InputStream is = response.getEntity().getContent();
- String result = inStream2String(is);
- Assert.assertEquals(result, "GET_SUCCESS");
- }
- }
- public void testPost() throws Exception {
- HttpClient client = new DefaultHttpClient();
- HttpPost post = new HttpPost(PATH + "/TestServlet");
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("id", "1001"));
- params.add(new BasicNameValuePair("name", "john"));
- params.add(new BasicNameValuePair("age", "60"));
- HttpEntity formEntity = new UrlEncodedFormEntity(params);
- post.setEntity(formEntity);
- HttpResponse response = client.execute(post);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- InputStream is = response.getEntity().getContent();
- String result = inStream2String(is);
- Assert.assertEquals(result, "POST_SUCCESS");
- }
- }
- public void testUpload() throws Exception {
- InputStream is = getContext().getAssets().open("books.xml");
- HttpClient client = new DefaultHttpClient();
- HttpPost post = new HttpPost(PATH + "/UploadServlet");
- InputStreamBody isb = new InputStreamBody(is, "books.xml");
- MultipartEntity multipartEntity = new MultipartEntity();
- multipartEntity.addPart("file", isb);
- multipartEntity.addPart("desc", new StringBody("this is description."));
- post.setEntity(multipartEntity);
- HttpResponse response = client.execute(post);
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- is = response.getEntity().getContent();
- String result = inStream2String(is);
- Assert.assertEquals(result, "UPLOAD_SUCCESS");
- }
- }
- //将输入流转换成字符串
- private String inStream2String(InputStream is) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[1024];
- int len = -1;
- while ((len = is.read(buf)) != -1) {
- baos.write(buf, 0, len);
- }
- return new String(baos.toByteArray());
- }
- }
以下是android自带的工具:
java.net包中的HttpURLConnection类
Get方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// Get方式请求
public
static
void
requestByGet()
throws
Exception {
String path =
"https://reg.163.com/logins.jsp?id=helloworld&pwd=android"
;
// 新建一个URL对象
URL url =
new
URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(
5
*
1000
);
// 开始连接
urlConn.connect();
// 判断请求是否成功
if
(urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte
[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET,
"Get方式请求成功,返回数据如下:"
);
Log.i(TAG_GET,
new
String(data,
"UTF-8"
));
}
else
{
Log.i(TAG_GET,
"Get方式请求失败"
);
}
// 关闭连接
urlConn.disconnect();
}
|
Post方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
// Post方式请求
public
static
void
requestByPost()
throws
Throwable {
String path =
"https://reg.163.com/logins.jsp"
;
// 请求的参数转换为byte数组
String params =
"id="
+ URLEncoder.encode(
"helloworld"
,
"UTF-8"
)
+
"&pwd="
+ URLEncoder.encode(
"android"
,
"UTF-8"
);
byte
[] postData = params.getBytes();
// 新建一个URL对象
URL url =
new
URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(
5
*
1000
);
// Post请求必须设置允许输出
urlConn.setDoOutput(
true
);
// Post请求不能使用缓存
urlConn.setUseCaches(
false
);
// 设置为Post请求
urlConn.setRequestMethod(
"POST"
);
urlConn.setInstanceFollowRedirects(
true
);
// 配置请求Content-Type
urlConn.setRequestProperty(
"Content-Type"
,
"application/x-www-form-urlencode"
);
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos =
new
DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判断请求是否成功
if
(urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte
[] data = readStream(urlConn.getInputStream());
Log.i(TAG_POST,
"Post请求方式成功,返回数据如下:"
);
Log.i(TAG_POST,
new
String(data,
"UTF-8"
));
}
else
{
Log.i(TAG_POST,
"Post方式请求失败"
);
}
}
|