本文主要是介绍Java发送httpPost,httpGet,httpDelete请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
业务场景:最近开发的项目使用的将文件图片和视频存储在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请求:
/*** 上传到minio*/
@RestController
@Slf4j
@RequestMapping("/backend/v1/upload")
public class UploadDIMSController {//MinioService@Autowiredprivate MinioService minioService;@Autowiredprivate UploadService uploadService;@Autowiredprivate ResourceService resourceService;@Autowiredprivate 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.登录获取tokenString token = loginDIMS(dimsConfig.getDimsSysCode(), dimsConfig.getUsername(), dimsConfig.getPassword());if (token == "获取token失败") {return JsonResponse.error("服务器异常,请稍后重试;" + token);}//2.获取批次号 和scanTimeHashMap<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 == "文件上传失败") {log.info("dims服务器异常,文件上传失败。");return JsonResponse.error("服务器异常,请稍后重试;" + imageId);}//4.上传业务信息List<InfosVO> arrayList = new ArrayList<>();InfosVO infosVO = new InfosVO();infosVO.setSysCode(dimsConfig.getDimsSysCode());infosVO.setIdentifier(dimsConfig.getIdentifier());infosVO.setImageId(imageId);infosVO.setImageName(file.getOriginalFilename());infosVO.setScanTime(scanTimeAndBatchCode.get("scanTime"));infosVO.setBatchCode(scanTimeAndBatchCode.get("batchCode"));infosVO.setOpId(dimsConfig.getOpId());infosVO.setFlwCode(dimsConfig.getDimsFlwCode());infosVO.setBisInfCode(dimsConfig.getClassCode());infosVO.setOrgCode(dimsConfig.getOrgCode());infosVO.setFunCode(dimsConfig.getDimsFunCode());infosVO.setMd5(getMd5(file));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 == "文件检索失败。") {log.info("dims服务器异常,文件检索失败。");return JsonResponse.error("服务器异常,请稍后重试;" + downloadUrl);}String dimsUrl = dimsConfig.getDownLoadJointFirstUrl() + downloadUrl;//获取上传到那个分类当中String categoryIds = MapUtils.getString(params, "category_ids");//传递管理员id,文件,和分类Resource resource = uploadService.storeDIMS(BCtx.getId(), file, categoryIds, dimsUrl);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) {// 将响应实体转换为字符串,响应的tokenString 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包返回的空字符,对接的系统的bugString 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进制return new BigInteger(1, digest).toString(16);} 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请求URLString 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) {// 将响应实体转换为字符串,响应的tokenString responseText = EntityUtils.toString(entity);return responseText;} else {return "获取token失败";}} finally {// 释放资源httpGet.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", "");
这个方法把这个小问题给解决了,也可以使用
String sanitizedText = responseText.trim(); //第二种方式去除空白字符
进行解决。
这篇关于Java发送httpPost,httpGet,httpDelete请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!