业务场景:最近开发的项目使用的将文件图片和视频存储在Minio当中,但是准备上线申请资源的时候申请不到资源,就临时决定使用厂商提供的Api接口进行文件图片和视频上传,然后就需要在后端进行登录,文件校验和文件存储和文件检索等http请求的书写,所以下面就分享给大家,如果有不足的地方还请多指教。
Maven依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version> <!-- 根据需要选择版本 -->
</dependency>
<!-- Apache HttpClient 依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 根据需要选择版本 -->
</dependency>
Controller:
httpPost请求:
@RestController
@Slf4j
@RequestMapping("/backend/v1/upload")
public class UploadDIMSController {
@Autowired
private UploadService uploadService;
@Autowired
private ResourceService resourceService;
@Autowired
private DIMSConfig dimsConfig;
/**
* DIMS文件上传的接口
* 统一使用一个接口
*/
@BackendPermissionMiddleware(slug = BPermissionConstant.RESOURCE_CATEGORY)
@PostMapping("/dims-upload")
public JsonResponse uploadDIMSHttp(@RequestParam HashMap<String, Object> params, MultipartFile file)
throws ServiceException {
if (file != null && !file.isEmpty()) {
try {
//1.登录获取token
String token = loginDIMS(dimsConfig.getDimsSysCode(), dimsConfig.getUsername(), dimsConfig.getPassword());
if (token.equals("获取token失败") ) {
return JsonResponse.error("服务器异常,请稍后重试;" + token);
}
//2.获取批次号 和scanTime
HashMap<String, String> scanTimeAndBatchCode = getBatchCode(dimsConfig.getDimsSysCode(), dimsConfig.getDimsFunCode(), token);
if (scanTimeAndBatchCode == null || scanTimeAndBatchCode.isEmpty()) {
log.info("dims服务器异常,获取批次号失败。");
return JsonResponse.error("服务器异常,请稍后重试");
}
//3.上传文件 获取imageID上传的唯一标识
String imageId = uploadFileAcquireImageId(file);
if (imageId.equals("文件上传失败")) {
log.info("dims服务器异常,文件上传失败。");
return JsonResponse.error("服务器异常,请稍后重试;" + imageId);
}
//4.上传业务信息
List<InfosVO> arrayList = new ArrayList<>();
InfosVO infosVO = new InfosVO();
arrayList.add(infosVO);
String code = uploadFileInfo(dimsConfig.getDimsSysCode(), token, dimsConfig.getDimsFunCode(), arrayList);
if (code != "1") {
log.info("dims服务器异常,上传业务信息失败。");
return JsonResponse.error("服务器异常,请稍后重试;");
}
//5.文件检索,将检索的地址直接保存到数据库当中直接返回给前端,前端进行处理
String downloadUrl = fileSearchAndSavaUrlToResource(dimsConfig.getDimsSysCode(), scanTimeAndBatchCode.get("batchCode"), token, dimsConfig.getDimsFunCode());
if (downloadUrl.equals("文件检索失败。") ) {
log.info("dims服务器异常,文件检索失败。");
return JsonResponse.error("服务器异常,请稍后重试;" + downloadUrl);
}
//获取上传到那个分类当中
String categoryIds = MapUtils.getString(params, "category_ids");
//传递管理员id,文件,和分类
Resource resource = uploadService.storeDIMS(BCtx.getId(), file, categoryIds, downloadUrl );
if (resource != null) {
//上传成功应该传递文件的路径
return JsonResponse.data("上传成功。");
} else {
return JsonResponse.error("上传失败。");
}
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException("Error uploading file to DIMS server");
}
} else {
return JsonResponse.error("文件为空。");
}
}
/**
* 1.登录获取token的方法
*/
public String loginDIMS(String sysCode, String userName, String password) throws IOException {
// 构建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HTTP POST 请求
HttpPost httpPost = new HttpPost(dimsConfig.getLoginUrl());
// 创建要传递的参数列表
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sysCode", sysCode));
params.add(new BasicNameValuePair("user", userName));
params.add(new BasicNameValuePair("pwd", password));
// 将参数设置到请求中
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
// 执行请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
// 处理响应
if (entity != null) {
// 将响应实体转换为字符串,响应的token
String responseText = EntityUtils.toString(entity);
return responseText;
} else {
return "获取token失败";
}
} finally {
// 释放资源
httpPost.releaseConnection();
}
}
/**
* 2.获取批次号
*/
public HashMap<String, String> getBatchCode(String sysCode, String funCode, String token) throws IOException {
HashMap<String, String> hashMap = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper();
// 构建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HTTP POST 请求
HttpPost httpPost = new HttpPost(dimsConfig.getBatchCodeUrl());
// 创建要传递的参数列表
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sysCode", sysCode));
params.add(new BasicNameValuePair("funCode", funCode));
params.add(new BasicNameValuePair("token", token));
// 将参数设置到请求中
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
// 执行请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
// 处理响应
if (entity != null) {
String responseText = EntityUtils.toString(entity);
log.info("getBatchCode-entity:{}", responseText);
//{"msg":"获取成功","data":"{\"scanTime\":\"2023-09-27 7:40:32\"}}"
// 去除jar包返回的空字符,对接的系统的bug
String sanitizedText = responseText.replace("\0", "");
// String sanitizedText = responseText.trim(); //第二种方式去除空白字符
//{"msg":"获取成功","data":{"scanTime":"2023-09-27 7:40:32","batchCode":"sdsdas211dsdx"}}
// 解析响应字符串
JSONObject entries = new JSONObject(sanitizedText);
hashMap.put("scanTime", entries.getJSONObject("data").getStr("scanTime"));
hashMap.put("batchCode", entries.getJSONObject("data").getStr("batchCode"));
return hashMap;
} else {
return new HashMap<>();
}
} finally {
// 释放资源
httpPost.releaseConnection();
}
}
/**
* 3.上传文件返回imageId
*/
public String uploadFileAcquireImageId(MultipartFile file) throws IOException {
// 构建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HTTP POST请求
HttpPost httpPost = new HttpPost(dimsConfig.getUploadMaxFileUrl());
// 创建一个包含文件和其他参数的多部分实体
/**
* 这是需要对接的这个接口也是用MultipartFile file进行接收的方式
* */
/* MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
httpPost.setEntity(builder.build());*/
/**
* 接口接收二进制数据
* */
// 设置请求头,告诉服务器请求体是二进制数据
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
// 将文件内容作为二进制数据设置为请求体
byte[] fileBytes = file.getBytes();
HttpEntity entity = new ByteArrayEntity(fileBytes);
httpPost.setEntity(entity);
try {
// 发送HTTP请求
HttpResponse response = httpClient.execute(httpPost);
// 处理响应
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
if (statusCode == 200) {
// 请求成功,根据响应处理结果
//这里可能还是要对responseBody进行空值截取
JSONObject entries = new JSONObject(responseBody);
return entries.getJSONObject("data").getStr("imageId");
} else {
// 请求失败,根据需要处理错误情况
// return new JsonResponse("Upload failed", responseBody);
return "文件上传失败";
}
} finally {
// 释放资源
httpPost.releaseConnection();
}
}
/**
* 4.上传业务信息
*/
// uploadFileInfo(dimsConfig.getDimsSysCode(),token,dimsConfig.getDimsFunCode(),arrayList);
public String uploadFileInfo(String sysCode, String token, String funCode, List<InfosVO> arrayList) throws IOException {
// 创建 ObjectMapper 对象,用于将对象转换为 JSON 字符串
ObjectMapper objectMapper = new ObjectMapper();
// 将 arrayList 转换为 JSON 字符串
String arrayListJson = objectMapper.writeValueAsString(arrayList);
// 构建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HTTP POST 请求
HttpPost httpPost = new HttpPost(dimsConfig.getUploadServiceInfoUrl());
// 创建要传递的参数列表
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sysCode", sysCode));
params.add(new BasicNameValuePair("token", token));
params.add(new BasicNameValuePair("funCode", funCode));
params.add(new BasicNameValuePair("infos", arrayListJson));//转换成JSON字符串
// 将参数设置到请求中
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
// 执行请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 处理响应
String responseBody = EntityUtils.toString(response.getEntity());
// 请求成功,根据响应处理结果
//这里可能还是要对responseBody进行空值截取
JSONObject entries = new JSONObject(responseBody);
return entries.getStr("code");
} finally {
// 释放资源
httpPost.releaseConnection();
}
}
/**
* 5.文件检索,获取 downloadUrl 进行拼接进行下载
*/
// fileSearchAndSavaUrlToResource(dimsConfig.getDimsSysCode(),scanTimeAndBatchCode.get("batchCode"),token,dimsConfig.getDimsFunCode());
public String fileSearchAndSavaUrlToResource(String sysCode, String batchCode, String token, String funCOde) throws IOException {
// 构建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HTTP POST 请求
HttpPost httpPost = new HttpPost(dimsConfig.getFileSearchUrl());
// 创建要传递的参数列表
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sysCode", sysCode));
params.add(new BasicNameValuePair("batchCode", batchCode));
params.add(new BasicNameValuePair("token", token));
params.add(new BasicNameValuePair("funCode", funCOde));
// 将参数设置到请求中
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
// 执行请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
log.info("fileSearchAndSavaUrlToResource-entity:{}", entity);
// 处理响应
if (entity != null) {
// 将响应实体转换为字符串
String responseText = EntityUtils.toString(entity);
JSONObject entries = new JSONObject(responseText);
if (entries.getStr("code") == "1") {
JSONArray dataArray = entries.getJSONArray("data");
JSONObject firstElement = dataArray.getJSONObject(0);
// 这里的 firstElement 就是第一个元素
return firstElement.getStr("downloadUrl");//获取 downloadUrl
} else {
return "文件检索失败。";
}
} else {
return "文件检索失败。";
}
} finally {
// 释放资源
httpPost.releaseConnection();
}
}
/**
* 获取上传文件的md5
*
* @param file
* @return
* @throws IOException
*/
public String getMd5(MultipartFile file) {
try {
//获取文件的byte信息
byte[] uploadBytes = file.getBytes();
// 拿到一个MD5转换器
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
//转换为16进制
String md5Hex = new BigInteger(1, digest).toString(16);
// 确保MD5值始终是32位
while (md5Hex.length() < 32) {
md5Hex = "0" + md5Hex;
}
return md5Hex;
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
httpGet请求:
public String loginDIMS(String sysCode, String userName, String password) throws IOException {
// 创建HTTP客户端
HttpClient httpClient = HttpClients.createDefault();
// 构建GET请求URL
String getUrl = dimsConfig.getLoginUrl() + "?sysCode=" + sysCode + "&user=" + userName + "&pwd=" + password;
// 创建HTTP GET请求
HttpGet httpGet = new HttpGet(getUrl);
try {
// 执行GET请求并获取响应
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 处理响应
if (entity != null) {
// 将响应实体转换为字符串,响应的token
String responseText = EntityUtils.toString(entity);
return responseText;
} else {
return "获取token失败";
}
} finally {
// 释放资源
httpGet.releaseConnection();
}
}
httpPut请求:
public JsonResponse httpPutMethod(@RequestParam HashMap<String, Object> params, MultipartFile file) throws IOException {
// 创建HTTP客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 构建PUT请求URL
String putUrl = "http://127.0.0.1:8080/test"; // 替换为实际的上传URL
// 创建HTTP PUT请求
HttpPut httpPut = new HttpPut(putUrl);
try {
// 创建请求体,使用MultipartEntityBuilder来构建
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//将file和parms参数放在请求体中
entityBuilder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
entityBuilder.addTextBody("params", new Gson().toJson(params), ContentType.APPLICATION_JSON);
// 设置请求实体
HttpEntity reqEntity = entityBuilder.build();
httpPut.setEntity(reqEntity);
// 执行PUT请求并获取响应
HttpResponse response = httpClient.execute(httpPut);
HttpEntity responseEntity = response.getEntity();
log.info("response:{}", response);
log.info("responseEntity:{}", responseEntity);
// 处理响应
if (responseEntity != null) {
// 将响应实体转换为字符串
String responseText = EntityUtils.toString(responseEntity);
log.info("responseText:{}", responseText);
if (responseText != null) {
return JsonResponse.data(responseText);
}
return JsonResponse.error("处理失败");
} else {
return JsonResponse.error("上传和处理失败");
}
} finally {
// 释放资源
httpPut.releaseConnection();
}
}
httpDelete请求:
public String deleteDIMS(String resourceUrl) throws IOException {
// 创建HTTP客户端
HttpClient httpClient = HttpClients.createDefault();
// 构建DELETE请求
HttpDelete httpDelete = new HttpDelete(resourceUrl);
try {
// 执行DELETE请求并获取响应
HttpResponse response = httpClient.execute(httpDelete);
int statusCode = response.getStatusLine().getStatusCode();
// 处理响应
if (statusCode == 200) {
// 处理成功的响应,根据需要返回结果
return "删除成功";
} else {
// 处理失败的响应,根据需要返回错误信息
return "删除失败,状态码:" + statusCode;
}
} finally {
// 释放资源
httpDelete.releaseConnection();
}
}
还有一个小知识:就是在对接厂商提供的接口的时候获取返回的JSON数据发现数据格式为
{"msg":"获取成功","data":"{\"scanTime\":\"2023-09-27 7:40:32\"}}"
其实就是JSON格式,但是就是识别不出来,最后发现这段数据中{”msg“前面有一个空字符,特别神奇,也不知道他们响应是如何响应的,然后我通过
String sanitizedText = responseText.replace("\0", "");
这个方法把这个小问题给解决了,也可以使用文章来源:https://www.toymoban.com/news/detail-729901.html
String sanitizedText = responseText.trim(); //第二种方式去除空白字符
进行解决。文章来源地址https://www.toymoban.com/news/detail-729901.html
到了这里,关于【Java】Java发送httpPost,httpGet,httpPut,httpDelete请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!