RestTemplateClient.java 2.35 KB
package com.topdraw.resttemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.topdraw.business.module.member.address.domain.MemberAddress;
import com.topdraw.business.module.member.domain.Member;
import com.topdraw.business.module.member.relatedinfo.domain.MemberRelatedInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class RestTemplateClient {

    private static RestTemplate restTemplate;

    private static String BASE_URL;

    @Autowired
    private Environment environment;

    @PostConstruct
    private void init() {
        BASE_URL = environment.getProperty("api.uc-service");
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时
        factory.setConnectTimeout(5000);
        // 设置读取超时
        factory.setReadTimeout(3000);
        restTemplate = new RestTemplate(factory);
    }

    public static String netImage(String imageUrl) {
        Image image = new Image(imageUrl);
        String entityBody = "";
        String url = BASE_URL + "/ucs/common/upload/netImage";
        log.info("request uc : url is " + url + ", memberId is " + com.alibaba.fastjson.JSONObject.toJSONString(image));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, image, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            entityBody  = responseEntity.getBody();
            JSONObject parseObject = JSON.parseObject(entityBody);
            List<Object> resultSet = (List)parseObject.get("resultSet");
            Object o = resultSet.get(0);
            return Objects.nonNull(o)?o.toString():"";
        }
        return entityBody;
    }

    @Data
    static class Image {

        private String url;

        public Image(String imageUrl){
            this.url = imageUrl;
        }

    }
}