springboot实现post请求

找了一堆,发现还是这个靠谱

package com.qishiyun.poplar.qlib.util;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.qishiyun.poplar.qlib.constant.ErrorCodeEnum;
import com.qishiyun.poplar.qlib.exception.QlibException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Slf4j
@RefreshScope
public class OssUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${newOss.baseUrl}")
    private String baseUrl;

    @Value("${newOss.stsUrl}")
    private String stsUrl;

    @Value("${newOss.appId}")
    private String appId;



    public String getOssTmpUrl(String ossUrl) {

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        JSONObject param = new JSONObject();
        param.put("ossUrl", ossUrl);
        param.put("appId",appId);
        param.put("expirationTime","1");
        HttpEntity<String> formEntity = new HttpEntity<String>(JSONUtil.toJsonStr(param), headers);


        String result = restTemplate.postForObject(baseUrl + stsUrl, formEntity, String.class);
        JSONObject resultJsonObject = JSONObject.parseObject(result);

        if (resultJsonObject.getInteger("code") == 200){
            JSONObject resultData = resultJsonObject.getJSONObject("data");
            String resultUrl = resultData.getString("ossSTSUrl");
            return resultUrl;
        }else {
            log.error("调用服务异常:{}",JSONUtil.toJsonStr(resultJsonObject.toJSONString()));
            throw new QlibException(ErrorCodeEnum.FAIL_GET_TMP_OSS_URL.code(), ErrorCodeEnum.FAIL_GET_TMP_OSS_URL.msg());
        }

    }

}

你可能感兴趣的:(springboot)