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

来源:互联网 发布:河南胸模招聘淘宝 编辑:程序博客网 时间:2024/05/21 14:03

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

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

        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>        </dependency>
/** * Created by weimiantong on 17/2/7. */@Service@Slf4jpublic 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封装了一层工具类如下

@Slf4jpublic 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 "";    }}
0 0
原创粉丝点击