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请求:

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper; // 需要导入 Jackson 库
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.playedu.api.BCtx;
import xyz.playedu.api.config.DIMSConfig;

import xyz.playedu.api.constant.BPermissionConstant;
import xyz.playedu.api.domain.InfosVO;
import xyz.playedu.api.domain.Resource;
import xyz.playedu.api.exception.ServiceException;
import xyz.playedu.api.middleware.BackendPermissionMiddleware;
import xyz.playedu.api.service.MinioService;
import xyz.playedu.api.service.ResourceService;
import xyz.playedu.api.service.UploadService;
import xyz.playedu.api.types.JsonResponse;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 上传到minio
 */
@RestController
@Slf4j
@RequestMapping("/backend/v1/upload")
public class UploadDIMSController {
    //MinioService
    @Autowired
    private MinioService minioService;

    @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 == "获取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 == "文件上传失败") {
                    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) {
                // 将响应实体转换为字符串,响应的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进制
            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请求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();
    }
}

        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(); //第二种方式去除空白字符

进行解决。

猜你喜欢

转载自blog.csdn.net/m0_64210833/article/details/133387364
今日推荐