HttpClient跨项目(服务端)调用方法例子
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
package
XX.XX.XX;
import
java.util.ArrayList;
import
java.util.List;
import
org.apache.http.NameValuePair;
import
org.apache.http.client.HttpClient;
import
org.apache.http.client.ResponseHandler;
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.impl.client.BasicResponseHandler;
import
org.apache.http.impl.client.DefaultHttpClient;
import
org.apache.http.message.BasicNameValuePair;
public
class
HttpClientTest {
public
static
void
main(String[] args) {
myPost();
}
/**
* @since 2013-8-14
* @Description: 以post方式请求网页
* @throws
* void
*/
public
static
void
myPost(){
//目标URL
String url =
"http://127.0.0.1:8080/testssi/MyTest.action"
;
//创建一个默认的HttpClient
HttpClient httpclient =
new
DefaultHttpClient();
try
{
//以post方式请求网页
HttpPost httppost =
new
HttpPost(url);
//添加HTTP POST参数
List <NameValuePair> nvps =
new
ArrayList <NameValuePair>();
nvps.add(
new
BasicNameValuePair(
"username"
,
"cz"
));
nvps.add(
new
BasicNameValuePair(
"password"
,
"123"
));
//将POST参数以UTF-8编码并包装成表单实体对象
httppost.setEntity(
new
UrlEncodedFormEntity(nvps,
"UTF-8"
));
//打印请求地址
System.out.println(
"executing request "
+ httppost.getRequestLine().getUri());
//创建响应处理器处理服务器响应内容
ResponseHandler<String> responseHandler =
new
BasicResponseHandler();
//执行请求并获取结果
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println(responseBody);
}
catch
(Exception e){
e.printStackTrace();
}
finally
{
// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
httpclient.getConnectionManager().shutdown();
}
}
/**
* @since 2013-8-14
* @Description: 以get方式请求网页
* @throws
* void
*/
public
static
void
myGet(){
//目标URL
String url =
"http://127.0.0.1:8080/testssi/MyTest.action"
;
//创建一个默认的HttpClient
HttpClient httpclient =
new
DefaultHttpClient();
try
{
//以get方式请求网页
HttpGet httpget =
new
HttpGet(url);
//打印请求地址
System.out.println(
"executing request "
+ httpget.getURI());
//创建响应处理器处理服务器响应内容
ResponseHandler<String> responseHandler =
new
BasicResponseHandler();
//执行请求并获取结果
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
}
catch
(Exception e){
e.printStackTrace();
}
finally
{
// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
httpclient.getConnectionManager().shutdown();
}
}
}
|
本文转自 艺晨光 51CTO博客,原文链接:http://blog.51cto.com/ycgit/1929268,如需转载请自行联系原作者