栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java | 使用HttpClient发送网络请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java | 使用HttpClient发送网络请求

Java | 使用HttpClient发送网络请求

使用HttpClient发送get或post请求,访问网络资源。


一、添加maven依赖

在解析数据时往往会配合json使用,所以同时添加fastjson依赖。


    org.apache.httpcomponents
    httpclient
    4.5.2



    com.alibaba
    fastjson
    1.2.56

二、使用方法 1. 发送get请求

请求方法

public static void get(String url) throws IOException {
    //请求参数设置
    RequestConfig requestConfig = RequestConfig.custom()
            //读取目标服务器数据超时时间
            .setSocketTimeout(10000)
            //连接目标服务器超时时间
            .setConnectTimeout(10000)
            //从连接池获取连接的超时时间
            .setConnectionRequestTimeout(10000)
            .build();

    CloseableHttpClient httpClient = null;
    HttpGet request = null;
    CloseableHttpResponse response = null;
    try {
        //创建HttpClient
        httpClient = HttpClients.createDefault();
        //使用url构建get请求
        request = new HttpGet(url);
        //填充请求设置
        request.setConfig(requestConfig);
        //发送请求,得到响应
        response = httpClient.execute(request);

        //获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        //状态码200 正常
        if (statusCode == 200) {
            //解析响应数据
            HttpEntity entity = response.getEntity();
            //字符串格式数据
            String string = EntityUtils.toString(entity, "UTF-8");
            System.out.println("字符串格式:" + string);
            //json格式数据
            JSONObject jsonObject = JSONObject.parseObject(string);
            System.out.println("json格式:" + jsonObject);
        } else {
            throw new HttpResponseException(statusCode, "响应异常");
        }
    } finally {
        if (response != null) {
            response.close();
        }
        if (request != null) {
            request.releaseConnection();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

模拟接口

@GetMapping("/getJsonData2")
public JSONObject getJson2(String name, int age) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", name);
    jsonObject.put("age", age);
    return jsonObject;
}

测试

使用 ?key1=value1&key2=value2 的形式传入参数

public static void main(String[] args) {
    String url = "http://localhost:8088/getJsonData2?name=jack&age=18";
    try {
        get(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

结果
2. 发送post请求

请求方法

public static void post(String url, Object param) throws Exception {
    //请求参数设置
    RequestConfig requestConfig = RequestConfig.custom()
            //读取目标服务器数据超时时间
            .setSocketTimeout(10000)
            //连接目标服务器超时时间
            .setConnectTimeout(10000)
            //从连接池获取连接的超时时间
            .setConnectionRequestTimeout(10000)
            .build();

    CloseableHttpClient httpClient = null;
    HttpPost request = null;
    CloseableHttpResponse response = null;
    try {
        //创建HttpClient
        httpClient = HttpClients.createDefault();
        //使用url构建post请求
        request = new HttpPost(url);
        //填充请求设置
        request.setConfig(requestConfig);
        //判断参数类型 可为Map或JSONObject
        if (null != param) {
            String type = param.getClass().toString();
            if (type.contains("JSON")) {
                StringEntity entity = new StringEntity(param.toString(), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                request.setEntity(entity);
            } else if (type.contains("Map")) {
                Map map = (Map) param;
                List pairs = new ArrayList<>();
                for (Map.Entry entry : map.entrySet()) {
                    pairs.add(new BasicNamevaluePair(entry.getKey(), String.valueOf(entry.getValue())));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded");
                request.setEntity(urlEncodedFormEntity);

            } else {
                throw new Exception("不支持的参数类型");
            }
            response = httpClient.execute(request);

            //获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            //状态码200 正常
            if (statusCode == 200) {
                //解析响应数据
                HttpEntity entity = response.getEntity();
                //字符串格式数据
                String string = EntityUtils.toString(entity, "UTF-8");
                System.out.println("字符串格式:" + string);
                //json格式数据
                JSONObject jsonObject = JSONObject.parseObject(string);
                System.out.println("json格式:" + jsonObject);
            } else {
                throw new HttpResponseException(statusCode, "响应异常");
            }
        }
    } finally {
        if (response != null) {
            response.close();
        }
        if (request != null) {
            request.releaseConnection();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

模拟接口

@PostMapping("/postData")
public JSONObject postData(@RequestBody JSONObject jsonObject) {
    jsonObject.put("time", System.currentTimeMillis());
    return jsonObject;
}

测试

public static void main(String[] args) {
    String url = "http://localhost:8088/postData";
    JSONObject param = new JSONObject();
    param.put("name", "chen");
    try {
        post(url, param);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

结果
3. 下载文件

请求方法

public static void downloadFile(String url, String savePath, String filename) throws IOException {
    //请求参数设置
    RequestConfig requestConfig = RequestConfig.custom()
            //读取目标服务器数据超时时间
            .setSocketTimeout(10000)
            //连接目标服务器超时时间
            .setConnectTimeout(10000)
            //从连接池获取连接的超时时间
            .setConnectionRequestTimeout(10000)
            .build();

    CloseableHttpClient httpClient = null;
    HttpGet request = null;
    CloseableHttpResponse response = null;
    try {
        //设置请求参数
        request = new HttpGet(url);
        request.setConfig(requestConfig);
        //发送请求
        httpClient = HttpClients.createDefault();
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            //输入流
            InputStream inputStream = entity.getContent();
            //根据ContentType获取文件类型
            String fileType = entity.getContentType().getValue();
            //得到文件后缀
            String suffix = fileType.split("/")[1];
            //路径末尾添加''
            if (!(savePath.endsWith("\") || savePath.endsWith("/"))) {
                savePath += File.separator;
            }
            //拼接文件保存绝对路径
            String filePath = savePath + filename + "." + suffix;
            //使用第三方包保存文件
            FileUtils.copyToFile(inputStream, new File(filePath));
        } else {
            throw new HttpResponseException(statusCode, "响应异常");
        }
    } finally {
        if (response != null) {
            response.close();
        }
        if (request != null) {
            request.releaseConnection();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}  

文件

https://img-home.csdnimg.cn/images/20201124032511.png

测试

public static void main(String[] args) {
    String url = "https://img-home.csdnimg.cn/images/20201124032511.png";
    String savePath = "D:\";
    String filename = "csdn";
    try {
        downloadFile(url, savePath, filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

结果

为了方便保存文件,使用了commons-io包中的FileUtils.copyToFile方法,依赖如下:


    commons-io
    commons-io
    2.6

不使用第三方依赖也可自己实现保存文件逻辑,其结果是一样的。

//FileUtils.copyToFile(inputStream, new File(filePath));

BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
三、总结

简单介绍了一下HttpClient发送get请求、post请求以及下载文件的使用方法,但HttpClient的使用方法肯定不局限于这几种,还有很多方法这里就不一一列举了,感兴趣的小伙伴可以自己摸索!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777393.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号