HttpClient 和HttpURLConnection 对比

本文介绍了一种在Android环境中检查网络连接状态并使用多种方法从网络下载数据的技术。包括使用HttpClient和HttpURLConnection进行数据下载,并提供了将数据保存到本地文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.administrator.downloadimage;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2017/5/4.
 */

public class HttpUtils {

    // 判断网络是否连接
    public static boolean isNetWorkConn(Context context) {
        // 需要权限:访问网络状态
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null) {
            return info.isConnected();
        } else {
            return false;
        }
    }

    // 下载获取数据
    public static byte[] httpClientLoadData(String path) {
        byte[] result = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(path);
            HttpResponse response = httpClient.execute(httpget);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toByteArray(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 下载获取数据
    public static byte[] httpURLConnLoadData(String path) {
        // 原生流操作
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            HttpURLConnection huc = (HttpURLConnection) new URL(path).openConnection();
            huc.setRequestMethod("GET");
            huc.connect();

            if (huc.getResponseCode() == 200) {
                bis = new BufferedInputStream(huc.getInputStream());
                int i = -1;
                byte[] bb = new byte[100];
                while ((i = bis.read(bb)) != -1) {
                    baos.write(bb, 0, i);
                    baos.flush();
                }
                bis.close();
                return baos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 下载网络数据到本地
    public static void httpURLConnectionLoadData(String path) {
        HttpURLConnection con = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            con = (HttpURLConnection) new URL(path).openConnection();
            con.setRequestMethod("GET");
            con.setUseCaches(false);// 忽略缓存   
            // 发送POST请求必须设置如下两行  
            //con.setDoOutput(true); // 开启输出流
            //con.setDoInput(true);
            //设置超时
            con.setConnectTimeout(5000);//连接超时
            con.setReadTimeout(5000);//读取数据超时
            // 设置通用的请求属性  
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.connect();

            if (con.getResponseCode() == 200) {
                bis = new BufferedInputStream(con.getInputStream());
                //写入本地工程文件中
                fos = new FileOutputStream(new File("my-file.txt"));
                int len = -1;
                byte[] bytes = new byte[1024];
                while ((len = bis.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                    fos.flush();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 关闭连接
        con.disconnect();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值