httpclient3.1简单使用

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();  
	    }  

	}

转载于:https://my.oschina.net/u/1376184/blog/685901

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值