您现在的位置是:首页 > 后台技术 > JavaJava

HttpClient(图文)

第十三双眼睛2020-03-22【Java】人已围观

简介HttpClient使用

httpclient简单使用
1引入依赖
<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
</dependency>
编写代码示例
public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet("http://www.tuicool.com");
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        String string = EntityUtils.toString(entity,"utf-8");
        System.out.println(string);
        response.close();
        httpClient.close();
}
有的时候,网站会做限制,比如下面这个网站:
http://www.tuicool.com,会出现如下的提示

这时候,只需要添加请求头信息就可以


简单的图片下载
public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet("http://www.zhaoybbk.com/d/file/p/2019/01-09/6e962e2af6101129845fd4c537f38e93.png");
        get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        if(entity !=null){
            String value = entity.getContentType().getValue();
            InputStream in = entity.getContent();
            FileUtils.copyToFile(in, new File("E://1.png"));
        }
        response.close();
        httpClient.close();
}
就可以将图片下载到指定位置
如果要使用代理的话,设置如下几行就可以
HttpHost proxy = new HttpHost("IP",port);
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
get.setConfig(config);
如果不超时,就可正常访问
设置超时时间
RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(10000).build();
get.setConfig(config);







 

Tags:HttpClient

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们