NetWorkUtils

来源:互联网 发布:2017前景行业知乎 编辑:程序博客网 时间:2024/06/05 18:52
package com.bwei.utils;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * 作者: * 时间:2017/9/11  9:28 * 类描述:网络请求数据工具类 */public class NetWorkUtil {    public String getStrJson(String strUrl){        URL url = null;        HttpURLConnection httpURLConnection = null;        String strJson = "";        InputStream inputStream = null;        try {            url = new URL(strUrl);            httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setConnectTimeout(5000);            httpURLConnection.setReadTimeout(5000);            int code = httpURLConnection.getResponseCode();            if (code == 200){                byte[] bt = new byte[1024];                int length = 0;                inputStream = httpURLConnection.getInputStream();                while ((length = inputStream.read(bt))!=-1){                    strJson += new String(bt,0,length);                }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (inputStream != null){                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return strJson;    }}