HttpClient发送GET请求
1, 创建HttpClient对象
2,创建HttpGet对象,指定请求地址(带参数)
3,使用HttpClient的execute(),方法执行HttpGet请求,得到HttpResponse对象
4,调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
5,调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
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
|
/**
* 通过HttpClient发送GET请求
*
* @param username
* @param password
* @return
*/
public
static
String loginByHttpClientGet(String username, String password) {
String path = http:
//192.168.0.107:8080/WebTest/LoginServerlet?username=
+ username + &password= + password;
HttpClient client =
new
DefaultHttpClient();
// 开启网络访问客户端
HttpGet httpGet =
new
HttpGet(path);
// 包装一个GET请求
try
{
HttpResponse response = client.execute(httpGet);
// 客户端执行请求
int
code = response.getStatusLine().getStatusCode();
// 获取响应码
if
(code ==
200
) {
InputStream is = response.getEntity().getContent();
// 获取实体内容
String result = StreamTools.streamToString(is);
// 字节流转字符串
return
result;
}
else
{
return
网络访问失败;
}
}
catch
(Exception e) {
e.printStackTrace();
return
网络访问失败;
}
}
|
HttpClient发送POST请求
1,创建HttpClient对象
2,创建HttpPost对象,指定请求地址
3,创建List,用来装载参数
4,调用HttpPost对象的setEntity()方法,装入一个UrlEncodedFormEntity对象,携带之前封装好的参数
5,使用HttpClient的execute()方法执行HttpPost请求,得到HttpResponse对象
6, 调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
7, 调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
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
|
/**
* 通过HttpClient发送POST请求
*
* @param username
* @param password
* @return
*/
public
static
String loginByHttpClientPOST(String username, String password) {
String path = http:
//192.168.0.107:8080/WebTest/LoginServerlet;
try
{
HttpClient client =
new
DefaultHttpClient();
// 建立一个客户端
HttpPost httpPost =
new
HttpPost(path);
// 包装POST请求
// 设置发送的实体参数
List<namevaluepair> parameters =
new
ArrayList<namevaluepair>();
parameters.add(
new
BasicNameValuePair(username, username));
parameters.add(
new
BasicNameValuePair(password, password));
httpPost.setEntity(
new
UrlEncodedFormEntity(parameters, UTF-
8
));
HttpResponse response = client.execute(httpPost);
// 执行POST请求
int
code = response.getStatusLine().getStatusCode();
if
(code ==
200
) {
InputStream is = response.getEntity().getContent();
String result = StreamTools.streamToString(is);
return
result;
}
else
{
return
网络访问失败;
}
}
catch
(Exception e) {
e.printStackTrace();
return
访问网络失败;
}
}</namevaluepair></namevaluepair>
|