通过Http获取远程数据 转化为Class类的通用方法

经常需要从远程获取数据转为实体类,可以通过泛型的实现getRemoteData 方法可以把远程获取的数据转化为自己定义的任何类

把获取的Json数据转为class 依赖 jackson

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
/**
 * Created by weimiantong on 17/2/7.
 */
@Service
@Slf4j
public class GetRemoteDataRepository {
    @Value("${service.shop.url}")
    private String shopUrl;

    @Value("${service.jqy.url}")
    private String jqyUrl;

    // 泛型处理远程数据转为实体类
    public <T> T getRemoteData(String uri, Class<T> clazz) {
        T out;
        String url = null;
        if (uri.startsWith("ws/shopws")) {
            url = shopUrl;
        } else if (uri.startsWith("ws/jqyws") || uri.startsWith("jqyHome") || uri.startsWith("ws/jqynewgroupws")) {
            url = jqyUrl;
        }
        if (url != null) {
            url += uri;
            try {
                String data = HttpUtil.getHttpUrlContent(url.toString(), "GBK", false, StringUtils.EMPTY);
                System.out.println(data);
                ObjectMapper objectMapper = new ObjectMapper();
                out = objectMapper.readValue(data, clazz);
                return out;
            } catch (Exception e) {
                log.error("{}", e);
                return null;
            }
        }
        return null;
    }
}

Http封装了一层工具类如下

@Slf4j
public class HttpUtil {

    private final static int CONNECT_TIME_OUT = 5000;
    private final static int READ_TIME_OUT = 5000;

    public static String getHttpUrlContent(String urlStr, String encoding, boolean isPost, String postBody) {
        return getHttpUrlContent(urlStr, encoding, isPost, postBody, CONNECT_TIME_OUT, READ_TIME_OUT);
    }

    public static String getHttpUrlContent(String url){
        return getHttpUrlContent(url,"UTF-8",false,null);
    }

    public static String getHttpUrlContent(String urlStr, String encoding, boolean isPost, String postBody, int connectTimeOut, int readTimeOut) {
        URL url = null;
        HttpURLConnection conn = null;
        long startTime = System.currentTimeMillis();
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            // post方法
            if (isPost) {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            // 设置连接超时和读取超时两个时间,防止进程被憋住
            conn.setConnectTimeout(connectTimeOut);
            conn.setReadTimeout(readTimeOut);
            // 建立连接
            conn.connect();
            if (isPost) {
                OutputStream out = conn.getOutputStream();
                out.write(postBody.getBytes(encoding));
                out.flush();
            }
            InputStream is = null;
            try {
                is = conn.getInputStream();
            } catch (IOException ex) {
                log.error("conn getInputStream error : ",ex);
                is = conn.getErrorStream();
            }
            BufferedReader breader = new BufferedReader(new InputStreamReader(is, encoding));
            char[] c_buf = new char[8192];
            StringBuffer buf = new StringBuffer("");
            int len = breader.read(c_buf, 0, 8192);
            while (len > 0) {
                buf.append(c_buf, 0, len);
                c_buf = new char[8192];
                len = breader.read(c_buf, 0, 8192);
            }
            breader.close();
            return buf.toString();
        } catch (Exception e) {
            log.error("error in getHttpUrlContent " + urlStr, e);
        } finally {
            url = null;
            if (conn != null) {
                conn.disconnect();
            }
            long t = System.currentTimeMillis() - startTime;
            if (t > 300)
                log.warn(urlStr + " cost " + t);
        }
        return "";
    }

    public static String getHttpUrlContent(String urlStr, String encoding, boolean isPost, String postBody, Map<String,String> headers, int connectTimeOut, int readTimeOut) {
        URL url = null;
        HttpURLConnection conn = null;
        long startTime = System.currentTimeMillis();
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String)iterator.next();
                conn.setRequestProperty(key, headers.get(key));
            }
            // post方法
            if (isPost) {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            // 设置连接超时和读取超时两个时间,防止进程被憋住
            conn.setConnectTimeout(connectTimeOut);
            conn.setReadTimeout(readTimeOut);
            // 建立连接
            conn.connect();
            if (isPost) {
                OutputStream out = conn.getOutputStream();
                out.write(postBody.getBytes(encoding));
                out.flush();
            }
            InputStream is = null;
            try {
                is = conn.getInputStream();
            } catch (IOException ex) {
                log.error("conn getInputStream error : ",ex);
                is = conn.getErrorStream();
            }
            BufferedReader breader = new BufferedReader(new InputStreamReader(is, encoding));
            char[] c_buf = new char[8192];
            StringBuffer buf = new StringBuffer("");
            int len = breader.read(c_buf, 0, 8192);
            while (len > 0) {
                buf.append(c_buf, 0, len);
                c_buf = new char[8192];
                len = breader.read(c_buf, 0, 8192);
            }
            breader.close();
            return buf.toString();
        } catch (Exception e) {
            log.error("error in getHttpUrlContent " + urlStr, e);
        } finally {
            url = null;
            if (conn != null) {
                conn.disconnect();
            }
            long t = System.currentTimeMillis() - startTime;
            if (t > 300)
                log.warn(urlStr + " cost " + t);
        }
        return "";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值