HttpRestClient.java 2.16 KB
package com.ui.http;

import com.ui.config.SystemConfig;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class HttpRestClient {

    private static final Logger logger = LoggerFactory
            .getLogger(HttpRestClient.class);

    private RestTemplate restTemplate;

    private SystemConfig systemConfig;

    public <T> T defaultPost(String uri, Object request, Class<T> responseType) {
        try {
            return restTemplate.postForObject(systemConfig.getServiceUrl() + uri, request,responseType);
        } catch (Exception e) {
            logger.error("postForObject failed!url:"+uri, e);
            return null;
        }
    }

    public <T> T defaultGet(String uri, Class<T> responseType,Map<String, ?> map) {
        try {
            StringBuilder url = new StringBuilder(uri);
            if(map != null){
                url.append("?");
                for (Map.Entry<String, ?> entry : map.entrySet()) {
                    url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                return restTemplate.getForObject(systemConfig.getServiceUrl() + url.toString().substring(0, url.length()-1), responseType);
            }
            return restTemplate.getForObject(systemConfig.getServiceUrl() + uri, responseType);
        } catch (Exception e) {
            logger.error("getForObject failed!url: "+uri, e);
            return null;
        }
    }

    public <T> T defaultGet(String uri, Class<T> responseType) {
        try {
            return restTemplate.getForObject(systemConfig.getServiceUrl() + uri, responseType);
        } catch (Exception e) {
            logger.error("getForObject failed!url: "+uri, e);
            return null;
        }
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    public void setSystemConfig(SystemConfig systemConfig) {
        this.systemConfig = systemConfig;
    }
}