1.httpclient采用的maven依赖
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
2.使用步骤
新建一个 HttpClient对象,作为客户端
新建请求方法对象,比如GetMethod 或 PostMethod
客户端执行所创建的GetMethod或PostMethod
获取返回的数据
释放连接
3.代码展示
public static void main(String[] args) { HttpClient httpClient = new HttpClient(); //创建客户端 String url ="http://news.163.com/16/0602/10/BOI4LUB400014PRF.html"; GetMethod getMethod = new GetMethod(url); try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { //执行成功的标示状态 System.err.println("Method failed: " + getMethod.getStatusLine()); } // 读取内容 byte[] responseBody = getMethod.getResponseBody(); // String res = getMethod.getResponseBodyAsString(); /* //Post PostMethod postMethod = new PostMethod(url); httpClient.executeMethod(postMethod); System.out.println(postMethod.getResponseBodyAsString());*/ 处理内容 String html = new String(responseBody); System.out.printlin(html); } catch (Exception e) { System.err.println("页面无法访问"); }finally{ //无论成功与否都要释放连接 getMethod.releaseConnection(); } }