通常情况下,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;q=+LcyJNcy3PxABvhVGmeSbaR45KcjXzSkYtemrW3XSgPEcmFV9cDIGhYjkw2ryK+hPHa29q1VhgYHJA4ckaNcT2dmIhHQSjBLJ9F0NHo
作为参数传入下方法即可将远程资源文件下载到本地临时文件夹,同时将本地临时文件夹内容读取上传至腾讯云COS
/*** 获取小能资源文件* @return*/publicStringgetSourceFile(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*/publicStringgetSourceFile(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; }