2.2 常用工具类 网络 支撑 JSON

网络可以选择例如okHttp,或者retrofit,也可以使用httpclient等。


httpUtils:

package com.qianfeng.loaderdemo.utils;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Set;
import java.util.zip.GZIPInputStream;


/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/11/23
 * Email: vhly@163.com
 */
public final class HttpUtils {


    public static final int CONNECT_TIMEOUT = 5000;


    private HttpUtils() {


    }


    public static byte[] doGet(String url) {
        return doGet(url, null);
    }


    public static byte[] doGet(String url, HashMap<String, String> headers) {
        byte[] ret = null;
        if (url != null) {
            HttpURLConnection conn = null;
            try {
                URL u = new URL(url);
                conn = (HttpURLConnection) u.openConnection();


                conn.setRequestMethod("GET");
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                setCommonHeaders(conn);




                if (headers != null) {
                    Set<String> keySet = headers.keySet();
                    for (String key : keySet) {
                        String value = headers.get(key);
                        conn.setRequestProperty(key, value);
                    }
                }


                conn.connect();


                int responseCode = conn.getResponseCode();


                if (responseCode == 200) {
                    ret = processResponse(conn);
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {


                StreamUtils.close(conn);
                //noinspection UnusedAssignment
                conn = null;
            }


        }
        return ret;
    }




    private static byte[] processResponse(HttpURLConnection conn) {
        byte[] ret = null;
        InputStream inputStream = null;
        try {
            String contentEncoding = conn.getContentEncoding();
            inputStream = conn.getInputStream();
            if ("gzip".equals(contentEncoding)) {
                inputStream = new GZIPInputStream(inputStream);
            }
            ret = StreamUtils.readStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            StreamUtils.close(inputStream);
        }
        return ret;
    }


    private static void setCommonHeaders(HttpURLConnection conn) {
        if (conn != null) {


            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Encoding", "gzip");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Accept", "application/*, text/*, */*");
            conn.setRequestProperty("X-Client", "Common HttpUtils");


        }
    }


}


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


StreamUtils.java:


package com.qianfeng.loaderdemo.utils;


import java.io.*;
import java.net.HttpURLConnection;


/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/11/24
 * Email: vhly@163.com
 */
public final class StreamUtils {


    private StreamUtils() {


    }


    public static void close(Object stream) {
        if (stream != null) {


            try {
                if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                } else if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                } else if (stream instanceof Reader) {
                    ((Reader) stream).close();
                } else if (stream instanceof Writer) {
                    ((Writer) stream).close();
                } else if (stream instanceof HttpURLConnection) {
                    ((HttpURLConnection) stream).disconnect();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }


        }
    }


    public static byte[] readStream(InputStream in) {
        byte[] ret = null;
        if (in != null) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            try {
                long len = readStream(in, bout);
                if (len > 0) {
                    ret = bout.toByteArray();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            close(bout);
            //noinspection UnusedAssignment
            bout = null;
        }
        return ret;
    }


    public static long readStream(InputStream in, OutputStream out) throws IOException {
        long ret = 0;
        if (in != null && out != null) {
            byte[] buf = new byte[1024];
            int len;
            while (true) {
                len = in.read(buf);
                if (len == -1) {
                    break;
                }
                out.write(buf, 0, len);
                ret += len;
            }
            //noinspection UnusedAssignment
            buf = null;
        }
        return ret;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值