OKHTTP

OKHTTP的简介

OKHTTP是一种第三方的网络下载工具,有get和post请求,一般get用来下载,post用来上传。一般是用来封装成工具类来使用的。

OKHTTP的get请求的工具类

    public void get(final Map<String,String> hashMap) {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(20,TimeUnit.SECONDS).build();
        final Request request = new Request.Builder().get().url(hashMap.get("data")).build();

        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.i(TAG, "onFailure: "+"失败");
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                Log.i(TAG, "onResponse: "+"开始下载");
                String pase = "/sdcard/Music";

                InputStream inputStream = response.body().byteStream();
                int len = 0;
                byte[] bytes = new byte[19];
                FileOutputStream fileOutputStream = new FileOutputStream(new File(pase + "/" + hashMap.get("name")+".mp3"));

                while ((len = inputStream.read(bytes)) != -1){
                    fileOutputStream.write(bytes);
                }
                Log.i(TAG, "onResponse: "+"下载完成!");
            }
        });
    }

OKHTTP的post请求的工具类

    public void post(String urlStr, HashMap<String,String> hashMap){
        OkHttpClient client = new OkHttpClient.Builder().build();

        FormBody.Builder formBody = new FormBody.Builder();
        for (String key:hashMap.keySet()){
            formBody.add(key,hashMap.get(key));
        }

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("hh",hashMap.get("name")+".mp3",
                RequestBody.create(MediaType.parse("media/mp3"),"/sdcard/"+hashMap.get("name")+".mp3"));
        MultipartBody body1 = builder.build();

        Request request = new Request.Builder().post(body1).url(urlStr).build();

        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.i(TAG, "onFailure: "+"失败");
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.i(TAG, "onResponse: "+"成功"+string);
            }
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值