RestTemplate请求第三方接口实战

package com.donlim.fms.common.srm;

import cn.hutool.http.HttpRequest;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.donlim.fms.common.utils.MyStringUtil;
import com.donlim.fms.exception.APIErrorCode;
import com.donlim.fms.exception.BizException;
import com.donlim.fms.model.seal.entity.Seal;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @Author lianshan
 * @ClassName SRMHttpUtil
 * @Description TODO
 * @createTime 2024/3/13 13:46
 * Version 1.0
 * SRM推送接口
 **/
@Component
public class SRMHttpUtil {

    @Resource
    RestTemplate restTemplate;

    /***
     * 获取SRM 认证token
     * @return
     */
    public  String post_srm_token(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ResponseEntity<String> response = restTemplate.postForEntity(SRM.TOKEN_URL, new HttpEntity<>(SRM.create_token_param(), headers), String.class);
        JSONObject json = JSONObject.parseObject(response.getBody());
        return json.getString(SRM.ACCESS_TOKEN);
    }

    /**
     * 印章请购单同步SRM接口
     * @return 是否推送成功
     */
    public  boolean post_seal_srm(Seal seal, String attachmentUulD, SealSrmDto dto){
        HttpHeaders headers = new HttpHeaders();
        String orgCode= seal.getU9_org_code();
        String deptCode= seal.getU9_dept_code();
        orgCode = MyStringUtil.getKuoHaoContentByRegex(orgCode);
        deptCode = MyStringUtil.getKuoHaoContentByRegex(deptCode);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add(SRM.AUTHORIZATION, SRM.BEARER +post_srm_token());
        Body body = new Body();
        body.setHeader(SRM.getHeader());
        List<SrmBody> list2 = new ArrayList<>();
        SrmBody srmBody = new SrmBody();
        srmBody.setDisplayPrNum(seal.getSealId());
        srmBody.setPrStatusCode(SRM.PRSTATUSCODE_NEW);
        srmBody.setEsPrTypeCode(SRM.SRM_QGD001);
        srmBody.setPrSourcePlatform(SRM.CATALOGUE);
//        srmBody.setCloseStatusCode("False");
        srmBody.setEsOuCode(orgCode);//传U9的组织编码
        srmBody.setUnitCode(deptCode);//传U9的部门编码
        srmBody.setCreator(seal.getApplyCode());//传创建人
        srmBody.setLocalCurrency("C001"); //币种 C001人民币
        srmBody.setEsAgentCode(seal.getEsAgentCode());//采购员
        srmBody.setAttributeVarchar15(dto.getAttributeVarchar15());//U9项目费用编码
        srmBody.setOriginalCurrency("C001");
        srmBody.setAttachmentUuid(attachmentUulD);
        List<PrLine> list = new ArrayList<>();
        PrLine line = new PrLine();
        line.setDisplayLineNum(1);
        line.setEsInvOrganizationCode(orgCode); //U9的组织编码
        line.setEsItemCode(dto.getEsItemCode());
        line.setIteminfoItemname(dto.getIteminfoItemname());
//        line.setEsPurCategoryCode("310");  // 传U9品类 N
        line.setEsUomCode(dto.getEsUomCode());
        line.setQuantity( new BigDecimal(seal.getZznumber()));
        LocalDate localDate = LocalDate.now();
        Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        Date date = Date.from(instant);
        line.setNeededDate(date);
        line.setItemSpecs(dto.getItemSpecs());
        line.setTaxIncludedUnitPrice(seal.getTaxIncludedUnitPrice());
        line.setEsTaxCode(dto.getEsTaxCode());
        line.setCurrencyCode("C001");
        line.setEsSupplierCode(dto.getEsSupplierCode());
        line.setEsSupplierName(dto.getEsSupplierName());
        line.setEsCostCode(dto.getAttributeVarchar15());
        line.setClosedFlag(0);
        line.setRemark("");
        line.setErpEditStatus("N");
        line.setAttachmentUuid(attachmentUulD);
        list.add(line);
        srmBody.setPrLineList(list);
        list2.add(srmBody);
        body.setBody(list2);
        ResponseEntity<String> response = restTemplate.exchange(SRM.SRM_URL, HttpMethod.POST, new HttpEntity<>(body, headers), String.class);
        JSONObject json = JSONObject.parseObject(response.getBody());
        if (json.getString("responseStatus").equals(SRM.ERROR)){
            throw new BizException(APIErrorCode.code.code500.getValue(), "推送SRM异常");
        }
        return json.getString("responseStatus").equals(SRM.SUCCESS);
    }

    /**
     * 推送附件获取uuid接口
     */
    public String get_srm_attachment_uuid(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add(SRM.AUTHORIZATION, SRM.BEARER + post_srm_token());
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add(SRM.TENANTID, "7");
        HttpEntity<MultiValueMap<String, String>> requestb = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(SRM.UUID_URL, requestb, String.class);
        JSONObject json = JSONObject.parseObject(response.getBody());
        return json.getString(SRM.CONTENT);
    }

    /**
     * 删除附件
     */
    public void post_srm_attachment_del(String attachmentUulD,String fileUrl) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add(SRM.AUTHORIZATION, SRM.BEARER + post_srm_token());
        HttpEntity<Object> requestEntity  = new HttpEntity<>(fileUrl, headers);
        String result = restTemplate.postForObject(SRM.DEl_ATTACHMENT_URL+"?"+"attachmentUUID="+attachmentUulD+"&bucketName=private-bucket&tenantId=7",requestEntity ,String.class);
        System.out.println("result = " +result);
    }



    /**
     * 发送附件接口
     */
    public String post_srm_attachment(String filepath, String attachmentUulD) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add(SRM.AUTHORIZATION, SRM.BEARER + post_srm_token());
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();

        File pdfFile = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(pdfFile);
        MultipartFile file = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        params.add("file", fileAsResource);
        params.add("attachmentUUID",attachmentUulD);
        params.add("bucketName","private-bucket");
        HttpEntity<MultiValueMap<String,Object>> requestEntity  = new HttpEntity<>(params, headers);
        String result = restTemplate.postForObject(SRM.ATTACHMENT_URL,requestEntity ,String.class);
        JSONObject json = JSONObject.parseObject(result);
        System.out.println("result = " + json.getString("fileUrl"));
        return json.getString("fileUrl");
    }

}

在使用RestTemplate请求第三方接口时,可以按照以下步骤进行操作: 1. 首先,需要创建一个RestTemplate对象。可以通过new RestTemplate()语句来实现。 2. 接下来,可以使用RestTemplate的getForObject()或postForObject()方法来发送GET或POST请求。这些方法可以接收两个参数:请求的URL和要发送的数据(如果有)。 3. 如果需要在请求头中设置查询条件,可以使用HttpHeaders类来创建请求头对象,并使用setContentType()方法设置请求头的Content-Type为application/json。然后,可以使用LinkedMultiValueMap类来创建一个MultiValueMap对象,将查询参数放入该对象中。 4. 最后,可以创建一个HttpEntity对象,将MultiValueMap对象和HttpHeaders对象作为参数传入。然后,将该对象作为参数传入getForObject()或postForObject()方法中,发送请求获取响应。 需要注意的是,引用提到了一个小坑:在设置请求头时,需要注意请求头的设置方式。具体原因未知。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [使用RestTemplate调用第三方接口获取数据。](https://blog.csdn.net/qq_40790367/article/details/108510538)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值