Java 请求头加header

简介: 讲述Java http请求添加header请求头操作

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

/*** @Description 可以添加headers 的请求工具类* @Author P001* @Date 2023/3/3 15:06* @Version 1.0*/publicclassHttpUtilsV2 {
privatestaticfinalCloseableHttpClienthttpclient=HttpClients.createDefault();
privatestaticfinalLoggerlog=LoggerFactory.getLogger(HttpUtilsV2.class);
privatestaticfinalStringuserAgent="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 返回字符串*/publicstaticStringsendGet(Stringurl, Stringparam, Map<String,String>headers) {
Stringresult=null;
CloseableHttpResponseresponse=null;
try {
StringurlNameString=url+"?"+param;
log.info("sendGet - {}", urlNameString);
HttpGethttpGet=newHttpGet(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);
HttpEntityentity=response.getEntity();
if (entity!=null) {
result=EntityUtils.toString(entity);
            }
        } catch (Exceptione) {
log.error(e.getMessage());
        } finally {
if (response!=null) {
try {
response.close();
                } catch (IOExceptione) {
log.error(e.getMessage());
                }
            }
        }
returnresult;
    }
/*** 发送HttpGet请求* 如果使用此方法,记得在finally中关闭response* @param url   url* @return 返回字符串*/publicstaticCloseableHttpResponsesendGet(Stringurl) {
CloseableHttpResponseresponse=null;
try {
log.info("sendGet - {}", url);
HttpGethttpGet=newHttpGet(url);
response=httpclient.execute(httpGet);
        } catch (Exceptione) {
log.error(e.getMessage());
        }
returnresponse;
    }
/*** 发送HttpPost请求** @param url     url* @param jsonStr 入参* @return 返回字符串*/publicstaticStringsendPost(Stringurl, StringjsonStr) {
Stringresult=null;
// 字符串编码StringEntityentity=newStringEntity(jsonStr, Consts.UTF_8);
// 设置content-typeentity.setContentType("application/json");
HttpPosthttpPost=newHttpPost(url);
// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);
// 接收参数设置httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(entity);
CloseableHttpResponseresponse=null;
try {
response=httpclient.execute(httpPost);
HttpEntityhttpEntity=response.getEntity();
result=EntityUtils.toString(httpEntity);
        } catch (IOExceptione) {
log.error(e.getMessage());
        } finally {
// 关闭CloseableHttpResponseif (response!=null) {
try {
response.close();
                } catch (IOExceptione) {
log.error(e.getMessage());
                }
            }
        }
returnresult;
    }
/*** 发送HttpPost请求** @param url url* @return 返回字符串*/publicstaticStringsendPost(Stringurl) {
Stringresult=null;
// 得到一个HttpPost对象HttpPosthttpPost=newHttpPost(url);
// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);
CloseableHttpResponseresponse=null;
try {
// 执行HttpPost请求,并得到一个CloseableHttpResponseresponse=httpclient.execute(httpPost);
// 从CloseableHttpResponse中拿到HttpEntityHttpEntityentity=response.getEntity();
// 将HttpEntity转换为字符串result=EntityUtils.toString(entity);
        } catch (IOExceptione) {
log.error(e.getMessage());
        } finally {
// 关闭CloseableHttpResponseif (response!=null) {
try {
response.close();
                } catch (IOExceptione) {
log.error(e.getMessage());
                }
            }
        }
returnresult;
    }
}

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

https://kefu.dongao.com/store/func/imagetrans/image2.php?f=o7AyJtNijflDAP1RHWeTarsltMgvRHX9Kg&amp;amp;q=+LcyJNcy3PxABvhVGmeSbaR45KcjXzSkYtemrW3XSgPEcmFV9cDIGhYjkw2ryK+hPHa29q1VhgYHJA4ckaNcT2dmIhHQSjBLJ9F0NHo

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

/*** 获取小能资源文件* @return*/@OverridepublicStringgetSourceFile(Stringurl, Datedate) {
Stringkey=null;
InputStreaminstream=null;
CloseableHttpResponseresponse=null;
FileOutputStreamout=null;
Stringtmppath=null;
try {
response=HttpUtilsV2.sendGet(url);
if (Objects.nonNull(response)) {
HttpEntityentity=response.getEntity();
//获取文件后缀名Headerheader=entity.getContentType();
Stringvalue=header.getValue();
inti=value.lastIndexOf("/");
Stringext=value.substring(i+1);
//文件存储路径Calendarcalendar=Calendar.getInstance();
calendar.setTime(date);
intyear=calendar.get(Calendar.YEAR);
intmonth=calendar.get(Calendar.MONTH) +1;
intday=calendar.get(Calendar.DAY_OF_MONTH);
StringfolderName=String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);
Randomrandom=newRandom();
StringfileName=date.getTime()+random.nextInt(100000)+"."+ext;
//先下载到本地,然后再读取,上传到costmppath=ConstantConfig.tmpPath+fileName;
//判断是否存在文件,不存在则新建Filefile=newFile(ConstantConfig.tmpPath);
if (!file.exists()) {
file.mkdirs();
                }
out=newFileOutputStream(tmppath);
entity.writeTo(out);
//再次读取上传到cosinstream=newFileInputStream(tmppath);
key=folderName+fileName;
CosClientUtil.uploadFileToCos(instream,key);
            }
        } catch (IOExceptione) {
e.printStackTrace();
        }finally {
try {
if (instream!=null) {
instream.close();
                }
if (response!=null) {
response.close();
                }
if (out!=null) {
out.close();
                }
if (tmppath!=null) {
newFile(tmppath).delete();
                }
            } catch (IOExceptione) {
e.printStackTrace();
            }
        }
returnkey;
    }

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

/*** 获取小能资源文件* @return*/@OverridepublicStringgetSourceFile(Stringurl, Datedate) {
Stringkey=null;
InputStreaminstream=null;
HttpClientclient=newHttpClient();
GetMethodget=null;
try {
get=newGetMethod(url);
inthttpStatus=client.executeMethod(get);
if (HttpStatus.OK.value() ==httpStatus) {
// 得到网络资源的字节数组,并写入文件byte[] result=get.getResponseBody();
instream=newByteArrayInputStream(result);
org.apache.commons.httpclient.Headerheader=get.getResponseHeader("Content-Type");
Stringvalue=header.getValue();
inti=value.lastIndexOf("/");
Stringext=value.substring(i+1);
//文件存储路径Calendarcalendar=Calendar.getInstance();
calendar.setTime(date);
intyear=calendar.get(Calendar.YEAR);
intmonth=calendar.get(Calendar.MONTH) +1;
intday=calendar.get(Calendar.DAY_OF_MONTH);
StringfolderName=String.format("%s/%s/%s/%s/", ConstantConfig.path, year, month, day);
Randomrandom=newRandom();
StringfileName=date.getTime()+random.nextInt(100000)+"."+ext;
key=folderName+fileName;
CosClientUtil.uploadFileToCos(instream,key);
            }
        } catch (IOExceptione) {
e.printStackTrace();
        }finally {
try {
if (instream!=null) {
instream.close();
                }
if (get!=null) {
get.releaseConnection();
                }
client.getHttpConnectionManager().closeIdleConnections(0);
            } catch (IOExceptione) {
e.printStackTrace();
            }
        }
returnkey;
    }
相关文章
|
8月前
|
Java 应用服务中间件 Spring
SpringBoot出现 java.lang.IllegalArgumentException: Request header is too large 解决方法
SpringBoot出现 java.lang.IllegalArgumentException: Request header is too large 解决方法
259 0
|
6月前
|
消息中间件 Java Maven
java.util.zip.ZipException: invalid LOC header (bad signature)
java.util.zip.ZipException: invalid LOC header (bad signature)
86 1
|
前端开发 Java
java在过滤器中为http请求加请求头header
现在有一个需求场景是,每一个请求我都需要在请求头里面加上token这个请求头,作为一种校验机制,传统的接口可以通过设置一个全局的变量,然后通过页面携带过来(大概就是先将我们的token放在session中,写一个服务用来获取session中的token,然后主页面用ajax调用接口,将token放在隐藏域中,然后将请求头放进来,用ajax方法,这里不想洗说了),但是有一种情况是通过页面传递的并不一定都会适用所有接口,比如上传和下载的接口有时候头里面就没有token参数,可能是上传和下载是用表单提交的 这个时候如何将请求头通过后台的方法加进来? 想到用过滤器,用后台方法强制加入请求头。
169 0
java202304java学习笔记第六十二天-ssm-获取请求头数据1
java202304java学习笔记第六十二天-ssm-获取请求头数据1
70 0
java202304java学习笔记第六十二天-ssm-获取请求头数据2
java202304java学习笔记第六十二天-ssm-获取请求头数据2
82 0
|
存储 缓存 Java
JVM - 剖析Java对象头Object Header之指针压缩
JVM - 剖析Java对象头Object Header之指针压缩
214 0
|
存储 Java C++
JVM - 剖析Java对象头Object Header之对象大小
JVM - 剖析Java对象头Object Header之对象大小
168 0
|
Java Spring
Java中restTemplate携带Header请求
Java中restTemplate携带Header请求
214 2
Java进行http请求时,放置会话信息到header里面
Java进行http请求时,放置会话信息到header里面
270 0
|
Web App开发 Java 程序员
【深入分析Java Web】HTTP解析-常见请求头/响应头/状态码
【深入分析Java Web】HTTP解析-常见请求头/响应头/状态码
357 0
【深入分析Java Web】HTTP解析-常见请求头/响应头/状态码