HttpURLConnection封装

HTTP数据传输工具类实现

public class HttpTransfer {
    protected static final String CHARSET = "UTF-8";
    protected static final int readTimeout = 5 * 1000;
    protected static final int connectTimeout = 5 * 1000;

    //单例模式
    private HttpTransfer() {
    }

    private static HttpTransfer httpTransfer;

    public static HttpTransfer getInstance() {
        if (httpTransfer == null) {
            synchronized (HttpTransfer.class) {
                if (httpTransfer == null) {
                    httpTransfer = new HttpTransfer();
                }
            }
        }
        return httpTransfer;
    }


    //获取HttpURLConnection
    public HttpURLConnection createConnection(String urls) throws Exception {
        URL url = new URL(urls);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        return connection;
    }

    //获取流
    public InputStream getInputStream(String urls) throws Exception {
        HttpURLConnection connection = createConnection(urls);
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        return inputStream;
    }

    //获取流数据
    public String getString(String urls) {
        InputStream in = null;
        ByteArrayOutputStream stream = null;
        String result = null;
        try {
            in = getInputStream(urls);
            stream = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                stream.write(b, 0, len);
            }
            result = stream.toString(CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public boolean shouldBeProcessed(HttpURLConnection conn) throws IOException {
        return conn.getResponseCode() == 200;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值