HttpURLConnection实现下载功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a_fly_pig/article/details/54020005
private String connectToTerminal(String urlStr) {
    LogUtils.i(TAG, "下载 url "+urlStr);
    LogUtils.i(TAG, "[jinxiuzhen]connectToTerminal();");
   
    URL url = null;
    HttpURLConnection connection = null;
    InputStream is = null;
    String result = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-API-KEY", LoginReceiver.keyToken);
        connection.setRequestProperty("url", urlStr);

        is = connection.getInputStream();
        InputStreamReader isReader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(isReader);
        String buffer = "";
        StringBuilder sb = new StringBuilder();
        while ((buffer = bufferedReader.readLine()) != null) {        
            sb.append(buffer);
        }
        result = sb.toString();
        LogUtils.i(TAG, "result=》"+result);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
    return result;
}

猜你喜欢

转载自blog.csdn.net/a_fly_pig/article/details/54020005