有时候我们在发送HTTP请求的时候会使用到POST方式,如果是传送普通的表单数据那将很方便,直接将参数到一个Key-value形式的Map中即可。但是如果我们需要传送的参数是Json格式的,会稍微有点麻烦,我们可以使用HttpClient类库提供的功能来实现这个需求。假设我们需要发送的数据是:
1
{
2
"blog": "http://www.iteblog.com",
3
"Author": "iteblog"
4
}
我们可以通过JSONObject够着Json:
1
JSONObject jsonObject = new JSONObject();
2
3
jsonObject.put("blog", "http://www.iteblog.com");
4
jsonObject.put("Author", "iteblog");
如果需要使用Post方式来发送这个数据,我们可以如下实现:
01
private HttpMethodBase createMethod(String url, int timeout) {
02
PostMethod method = null;
03
try {
04
method = new PostMethod(url);
05
JSONObject jsonObject = new JSONObject();
06
07
jsonObject.put("blog", "http://www.iteblog.com");
08
jsonObject.put("Author", "iteblog");
09
10
String transJson = jsonObject.toString();
11
RequestEntity se = new StringRequestEntity(transJson, "application/json", "UTF-8");
12
method.setRequestEntity(se);
13
//使用系统提供的默认的恢复策略
14
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
15
//设置超时的时间
16
method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout);
17
} catch (IllegalArgum www.hbbz08.com entException e) {
18
logger.error("非法的URL:{}", url);
19
} catch (UnsupportedEncodingException e) {
20
e.printStackTrace();
21
}
22
23
return method;
24
}
我们通过StringRequestEntity来构造请求实体,在这里,StringRequestEntity将接收三个参数,如下:
1
public StringRequestEntity(String content, String contentType, String charset)
2
throws UnsupportedEncodingException
其中参数content就是我们需要传输的数据;contentType是传送数据的格式,因为我们的数据格式是json的,所以contentType必须填写application/json(更多的contentType可以参见《HTTP Content-Type常用一览表》);charset是字符集编码。
然后我们再通过HttpClient对象的executeMethod方法来执行:
查看源代码打印帮助
1
int statusCode = httpClient.executeMethod(getMethod);
2
//只要在获取源码中,服务器返回的不是200代码,则统一认为抓取源码失败,返回null。
3
if (statusCode != HttpStatus.SC_OK) {
4
logger.error("Method failed: " + getMethod.getStatusLine() + "\tstatusCode: " + statusCode);
5
return null;
6
}