okhttp下载

1、依赖
compile 'com.zhy:okhttputils:2.6.2'

2、代码
public class MainActivity extends AppCompatActivity {

    private File file;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        OkHttpUtils.get()
                .url("http://huixinguiyu.cn/Assets/js/newsnew.js")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        String string = response.toString();
                        Toast.makeText(MainActivity.this,string, Toast.LENGTH_SHORT).show();
                    }
                });
        file = new File(Environment.getExternalStorageDirectory().getPath());

    }
    public void bbb(View v){
        progressBar.setVisibility(View.VISIBLE);
        OkHttpUtils
                .get()
                .url("http://p.gdown.baidu.com/e96035c05cfbd104bc614338d32e4998cf247dcb6b1d2f55352c28c485a21dc66ba8b52319123d749562b790fc47aaaee5da5908708263ce0b1692be82a460934eed49f570b9c59411293bb6bbc5eaa6b5d33a12fa8942809ab5006d401340245313c56321cf811b955d8594032edf172207325d3d4fe11fd2a043066ab78e7def5069cf551eefddc1250aa4f4faf971cddb65081a3004655f51e0adfa56339673d241fd87d214181c62654fcf4ec14746c495a66bbafe057a887ec1a8741de6fec48d8ed0e75ab7e22a9538a70aeb0d590439066f50f5505137d99b62a87fa5")
//                .url("https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=2207238342,3445927478&fm=58&u_exp_0=1640204727,3112622068&fm_exp_0=86&bpow=512&bpoh=512")
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(),"shf.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(MainActivity.this,e+"",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        progressBar.setProgress((int)(100*progress));

                    }

                    @Override
                    public void onResponse(File response, int id) {
                        String string = response.toString();
                        Toast.makeText(MainActivity.this,string,Toast.LENGTH_LONG).show();

                        if (progressBar.getProgress()==progressBar.getMax()){
                            Toast.makeText(MainActivity.this,"ok",Toast.LENGTH_LONG).show();

                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
                            startActivity(intent);

                        }
                    }

                });
    }
}

OkHttp是一个轻量级、高效的HTTP客户端库,由Square公司维护,它非常适合于Android应用和服务器之间的网络通信。如果你想用OkHttp下载文件,可以按照以下步骤操作: 1. 首先,添加依赖到你的项目中。如果你使用的是Gradle构建工具,可以在`build.gradle`文件的dependencies块中加入: ```groovy implementation 'com.squareup.okhttp3:okhttp:4.x.y' ``` 2. 创建一个OkHttpClient实例,并设置请求头(如支持流式传输): ```java OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时 .readTimeout(10, TimeUnit.SECONDS) // 设置读取超时 .build(); Request request = new Request.Builder() .url("https://example.com/file.zip") // 替换为你需要下载的文件URL .header("User-Agent", "MyApp/1.0") // 添加请求头信息 .build(); ``` 3. 使用OkHttpClient发起GET请求并处理响应: ```java Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } // 获取文件名,如果没有指定则默认文件名为download.txt String fileName = response.request().url().path(); try (ResponseBody body = response.body()) { // 将响应体内容写入本地文件 Files.copy(body.byteStream(), new File(fileName)); } ``` 4. 当然,为了更优雅地处理下载进度,你可以选择使用RequestBody的source方法获取一个Source,然后通过ProgressListener监听下载进度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值