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;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;
}