Java 请求头加header

Java 请求头加header

通常情况下,java的http请求接口可以无需加header,但也有的第三方接口强制要求将accesstoken放在请求头中,而不能作为普通参数传递,这样就需要在请求头中加header,这里写了几个http请求工具类的方法,希望对大家有帮助

java 复制代码
/**

 * @Description 可以添加headers 的请求工具类

 * @Author P001

 * @Date 2023/3/3 15:06

 * @Version 1.0

 */

public class HttpUtilsV2 {

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    private static final Logger log = LoggerFactory.getLogger(HttpUtilsV2.class);

    private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";



    /**

     * 发送HttpGet请求

     *

     * @param url   url

     * @param param param

     * @return 返回字符串

     */

    public static String sendGet(String url, String param, Map<String,String> headers) {

        String result = null;

        CloseableHttpResponse response = null;

        try {

            String urlNameString = url + "?" + param;

            log.info("sendGet - {}", urlNameString);

            HttpGet httpGet = new HttpGet(urlNameString);

            httpGet.setHeader("User-Agent", userAgent);

            if (Objects.nonNull(headers)) {

                Set<Map.Entry<String, String>> entries = headers.entrySet();

                if (CollectionUtils.isNotEmpty(entries)) {

                    for (Map.Entry<String, String> entry : entries) {

                        httpGet.setHeader(entry.getKey(), entry.getValue());

                    }

                }

            }

            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();

            if (entity != null) {

                result = EntityUtils.toString(entity);

            }

        } catch (Exception e) {

            log.error(e.getMessage());

        } finally {

            if (response != null) {

                try {

                    response.close();

                } catch (IOException e) {

                    log.error(e.getMessage());

                }

            }

        }

        return result;

    }


    /**

     * 发送HttpGet请求

     * 如果使用此方法,记得在finally中关闭response

     * @param url   url

     * @return 返回字符串

     */

    public static CloseableHttpResponse sendGet(String url) {

        CloseableHttpResponse response = null;

        try {

            log.info("sendGet - {}", url);

            HttpGet httpGet = new HttpGet(url);

            response = httpclient.execute(httpGet);

        } catch (Exception e) {

            log.error(e.getMessage());

        }

        return response;

    }


    /**

     * 发送HttpPost请求

     *

     * @param url     url

     * @param jsonStr 入参

     * @return 返回字符串

     */

    public static String sendPost(String url, String jsonStr) {

        String result = null;

        // 字符串编码

        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);

        // 设置content-type

        entity.setContentType("application/json");

        HttpPost httpPost = new HttpPost(url);

        // 防止被当成攻击添加的

        httpPost.setHeader("User-Agent", userAgent);

        // 接收参数设置

        httpPost.setHeader("Accept", "application/json");

        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);

            HttpEntity httpEntity = response.getEntity();

            result = EntityUtils.toString(httpEntity);

        } catch (IOException e) {

            log.error(e.getMessage());

        } finally {

            // 关闭CloseableHttpResponse

            if (response != null) {

                try {

                    response.close();

                } catch (IOException e) {

                    log.error(e.getMessage());

                }

            }

        }

        return result;

    }



    /**

     * 发送HttpPost请求

     *

     * @param url url

     * @return 返回字符串

     */

    public static String sendPost(String url) {

        String result = null;

        // 得到一个HttpPost对象

        HttpPost httpPost = new HttpPost(url);

        // 防止被当成攻击添加的

        httpPost.setHeader("User-Agent", userAgent);

        CloseableHttpResponse response = null;

        try {

            // 执行HttpPost请求,并得到一个CloseableHttpResponse

            response = httpclient.execute(httpPost);

            // 从CloseableHttpResponse中拿到HttpEntity

            HttpEntity entity = response.getEntity();

            // 将HttpEntity转换为字符串

            result = EntityUtils.toString(entity);

        } catch (IOException e) {

            log.error(e.getMessage());

        } finally {

            // 关闭CloseableHttpResponse

            if (response != null) {

                try {

                    response.close();

                } catch (IOException e) {

                    log.error(e.getMessage());

                }

            }

        }

        return result;

    }

}

另外也可以基于当前请求工具类获取远程资源文件并下载到本地,比如资源路径:

复制代码
https://kefu.test.com/store/func/imagetrans/image2.php?f=o7AyJtNijflDAP1RHWeTarsltMgvRHX9Kg&amp;amp;q=+LcyJNcy3PxABvhVGmeSbaR45KcjXzSkYtemrW3XSgPEcmFV9cDIGhYjkw2ryK+hPHa29q1VhgYHJA4ckaNcT2dmIhHQSjBLJ9F0NHo

作为参数传入下方法即可将远程资源文件下载到本地临时文件夹,同时将本地临时文件夹内容读取上传至腾讯云COS

java 复制代码
/**

     * 获取小能资源文件

     * @return

     */

    @Override

    public String getSourceFile(String url, Date date) {

        String key = null;

        InputStream instream = null;

        CloseableHttpResponse response = null;

        FileOutputStream out = null;

        String tmppath = null;

        try {

            response = HttpUtilsV2.sendGet(url);

            if (Objects.nonNull(response)) {

                HttpEntity entity = response.getEntity();


                //获取文件后缀名

                Header header = entity.getContentType();

                String value = header.getValue();

                int i = value.lastIndexOf("/");

                String ext = value.substring(i + 1);

                //文件存储路径

                Calendar calendar = Calendar.getInstance();

                calendar.setTime(date);

                int year = calendar.get(Calendar.YEAR);

                int month = calendar.get(Calendar.MONTH) + 1;

                int day = calendar.get(Calendar.DAY_OF_MONTH);

                String folderName = String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);


                Random random = new Random();

                String fileName = date.getTime()+ random.nextInt(100000)+"."+ext;

                //先下载到本地,然后再读取,上传到cos

                tmppath = ConstantConfig.tmpPath + fileName;

                //判断是否存在文件,不存在则新建

                File file = new File(ConstantConfig.tmpPath);

                if (!file.exists()) {

                    file.mkdirs();

                }

                out = new FileOutputStream(tmppath);

                entity.writeTo(out);

                //再次读取上传到cos

                instream = new FileInputStream(tmppath);

                key = folderName + fileName;

                CosClientUtil.uploadFileToCos(instream,key);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }finally {

            try {

                if (instream != null) {

                    instream.close();

                }

                if (response != null) {

                    response.close();

                }

                if (out != null) {

                    out.close();

                }

                if (tmppath != null) {

                    new File(tmppath).delete();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return key;

    }

当然也可以不经过下载到本地临时目录再上传的方式直接将远程资源文件上传到腾讯云COS

java 复制代码
  /**

     * 获取小能资源文件

     * @return

     */

    @Override

    public String getSourceFile(String url, Date date) {

        String key = null;

        InputStream instream = null;

        HttpClient client = new HttpClient();

        GetMethod get = null;

        try {

            get = new GetMethod(url);

            int httpStatus = client.executeMethod(get);


            if (HttpStatus.OK.value() == httpStatus) {

                // 得到网络资源的字节数组,并写入文件

                byte[] result = get.getResponseBody();

                instream = new ByteArrayInputStream(result);

                org.apache.commons.httpclient.Header header = get.getResponseHeader("Content-Type");

                String value = header.getValue();

                int i = value.lastIndexOf("/");

                String ext = value.substring(i + 1);

                //文件存储路径

                Calendar calendar = Calendar.getInstance();

                calendar.setTime(date);

                int year = calendar.get(Calendar.YEAR);

                int month = calendar.get(Calendar.MONTH) + 1;

                int day = calendar.get(Calendar.DAY_OF_MONTH);

                String folderName = String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);


                Random random = new Random();

                String fileName = date.getTime()+ random.nextInt(100000)+"."+ext;

                key = folderName + fileName;

                CosClientUtil.uploadFileToCos(instream,key);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }finally {

            try {

                if (instream != null) {

                    instream.close();

                }

                if (get != null) {

                    get.releaseConnection();

                }

                client.getHttpConnectionManager().closeIdleConnections(0);

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return key;

    }
相关推荐
Cat_Rocky30 分钟前
k8s-持久化存储,粗浅学习
java·学习·kubernetes
楼兰公子37 分钟前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
知识领航员1 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
吴声子夜歌1 小时前
Go——并发编程
开发语言·后端·golang
释怀°Believe1 小时前
Spring解析
java·后端·spring
ooseabiscuit1 小时前
Laravel4.x:现代PHP框架的奠基之作
java·开发语言·php
c1s2d3n4cs2 小时前
Qt模仿nlohmann::json进行序列化和反序列化
开发语言·qt·json
节奏昂2 小时前
【一份基础软件的下载地址和安装地址】
java
没什么本事2 小时前
关于C# panel 添加lable问题 -- 明确X和Y 位置错误
android·java·c#
AiTop1003 小时前
Claude Code 推出 Agent View:命令行编程正式进入“多线程并发“时代
开发语言·人工智能·ai·aigc