HttpClient

jdk原生态

package com.shengun.httpclient.test;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public class TestUrlConnection {
    @Test
    public void test01() throws Exception {
        String urlStr = "https://www.baidu.com";
        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
        httpURLConnection.setRequestMethod("GET");
        InputStream is = httpURLConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }
    }
}

HttpClient

@Test
    public void test01(){
        CloseableHttpClient client = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com";

        HttpGet httpGet = new HttpGet(urlStr);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(content);
            EntityUtils.consume(entity);
        }catch (Exception e){

        }finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Get

@Test
    public void test02() throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String password = URLEncoder.encode("abs782u8|sss",StandardCharsets.UTF_8.name());
        String urlStr = "http://localhost:8080/user?username=斩杀&password="+password;

        HttpGet httpGet = new HttpGet(urlStr);
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            //获取响应状态
            StatusLine statusLine = response.getStatusLine();
            System.out.println("响应状态:" + statusLine);
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
                System.out.println("响应头:" + allHeader.getName() + "的值是:" + allHeader.getValue());
            }
            HttpEntity entity = response.getEntity();
            System.out.println("获取内容类型:" + entity.getContentType());
            String content = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            System.out.println(content);
            EntityUtils.consume(entity);
        }catch (Exception e){

        }finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

下载图片

@Test
    public void test03(){
        String picUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202004%2F17%2F20200417121646_crtyi.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637156723&t=d88c7fb427cf5236762035bfd2fd518a";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(picUrl);
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            //获取响应状态
            HttpEntity entity = response.getEntity();
            //判断图片后缀
            String contentType = entity.getContentType().getValue();
            System.out.println(contentType);
            String suffix = ".jpg";
            if (contentType.contains("jpg") || contentType.contains("jpeg")) {
                suffix = ".jpg";
            }else if(contentType.contains("bmp")||contentType.contains("bitmap")){
                suffix = ".bmp";
            }else if(contentType.contains("png")){
                suffix = ".png";
            }
            else if(contentType.contains("gif")){
                suffix = ".gif";
            }

            byte[] bytes = EntityUtils.toByteArray(entity);
            String localAbsolth = "F:\\workpace\\app-workspace\\SpringClound-lean01\\src\\main\\resources\\pic\\a" + suffix;
            FileOutputStream fos = new FileOutputStream(localAbsolth);
            fos.write(bytes);
            fos.flush();
            fos.close();
            EntityUtils.consume(entity);
        }catch (Exception e){

        }finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值