有时候我们在发送HTTP请求的时候会使用到POST方式,如果是传送普通的表单数据那将很方便,直接将参数到一个Key-value形式的Map中即可。但是如果我们需要传送的参数是Json格式的,会稍微有点麻烦,我们可以使用HttpClient类库提供的功能来实现这个需求。假设我们需要发送的数据是:
"blog": "", "Author": "iteblog"
我们可以通过JSONObject够着Json:
JSONObject jsonObject = new JSONObject(); jsonObject.put("blog", ""); jsonObject.put("Author", "iteblog");
如果需要使用Post方式来发送这个数据,我们可以如下实现:
private HttpMethodBase createMethod(String url, int timeout) { PostMethod method = null; try { method = new PostMethod(url); JSONObject jsonObject = new JSONObject(); jsonObject.put("blog", ""); jsonObject.put("Author", "iteblog"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson, "application/json", "UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout); } catch (IllegalArgumentException e) { logger.error("非法的URL:{}", url); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return method;
我们通过StringRequestEntity来构造请求实体,在这里,StringRequestEntity将接收三个参数,如下:
public StringRequestEntity(String content, String contentType, String charset) throws UnsupportedEncodingException
其中参数
content
就是我们需要传输的数据;
contentType
是传送数据的格式,因为我们的数据格式是json的,所以
contentType
必须填写
application/json
(更多的contentType可以参见
《HTTP Content-Type常用一览表》
);
charset
是字符集编码。
然后我们再通过HttpClient对象的executeMethod方法来执行:
int statusCode = httpClient.executeMethod(getMethod); //只要在获取源码中,服务器返回的不是200代码,则统一认为抓取源码失败,返回null。 if (statusCode != HttpStatus.SC_OK) { logger.error("Method failed: " + getMethod.getStatusLine() + "\tstatusCode: " + statusCode); return null;
pom.xml文件的关键内容
<dependencies> <!--网络爬虫--> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.3.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>14.0.1</version> </dependency> <dependency>