HttpClient--入门

来源:互联网 发布:牵引变电所接地网优化 编辑:程序博客网 时间:2024/05/17 09:36

1 获取网页代码

public static void main(String[] args){        CloseableHttpClient httpClient = HttpClients.createDefault();//创建httpclient实例        HttpGet httpGet=new HttpGet("http://www.open1111.com");        CloseableHttpResponse response=null;        try {             response= httpClient.execute(httpGet);        } catch (ClientProtocolException e) {//协议异常            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        HttpEntity entity=response.getEntity();        try {            String string = EntityUtils.toString(entity,"utf-8");            System.out.println(string);        } catch (ParseException e) {//解析异常            e.printStackTrace();        } catch (IOException e) {//IO异常            e.printStackTrace();        }        try {            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }

2 获取相关信息
2.1 获取返回的状态信息:

CloseableHttpResponse response = httpClient.execute(httpGet);System.out.println("Status:"+response.getStatusLine().getStatusCode());

2.2 获取返回头信息中ContentType的值

System.out.println(entity.getContentType().getValue());

摘自:http://www.open1111.com

3 获取图片

public static void main(String[] args) throws IOException {        CloseableHttpClient httpClient = HttpClients.createDefault();// 创建httpclient实例        HttpGet httpGet = new HttpGet("https://www.baidu.com/img/bd_logo1.png");        //设置请求头信息User-Agent模拟浏览器        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/56.0");        CloseableHttpResponse response = httpClient.execute(httpGet);        HttpEntity entity = response.getEntity();        if(entity!=null){            System.out.println("ContentType:"+entity.getContentType().getValue());            InputStream content = entity.getContent();            //复制文件到本地            //org.codehaus.plexus.util.FileUtils.copyURLToFile(new URL("https://www.baidu.com/img/bd_logo1.png"), new File("D:/image.png"));            FileUtils.copyToFile(content,new File("D:/image.png"));        }        response.close();        httpClient.close();        System.out.println("run over");    }
原创粉丝点击