day30 OkHttp

OkHttp的使用

package com.example.day30;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 1.okhttp:网络请求框架
 * 2.功能:get请求  post请求  下载文件  上传文件
 * 3.实现流程
 * (1)导入依赖: implementation 'com.squareup.okhttp3:okhttp:3.12.1'
 * (2)创建客户端:OkHttpClient
 * (3)创建请求对象:Request
 * (4)客户端发送请求得到一个连接:Call
 * (5)得到响应:Response
 * 4.get和post的区别:
 * (1)get请求向服务器获取数据:下载音乐 下载图片  json数据
 * (2)post向服务器提交数据:登陆注册(用户名和密码) 上传文件   json数据
 * (3)get请求 明文 把数据暴露在网址上  post请求 密文 用户名和密码放在请求体
 *
 */
public class MainActivity extends AppCompatActivity {
    private String get="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
    private String post="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&";
    private static final String TAG = "123321";
    private ProgressBar pb;
    private InputStream is;

    @SuppressLint("HandlerLeak")
    private Handler han=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if( msg.what==222){
                pb.setMax(Integer.parseInt(msg.obj.toString()));
            }else {
                int arg1 = msg.arg1;
                pb.setProgress(arg1);
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},222);

        pb=findViewById(R.id.main_progress);
        pb.setMax(100);

    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.main_button_get:
                get();
                break;
            case R.id.main_button_post:
                post();
                break;
            case R.id.main_button_downLoad:
                load();
                break;
            case R.id.main_button_upLoad:
                upload();
                break;
        }
    }

    private void upload() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient client = builder.readTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).build();
        Request.Builder builder1 = new Request.Builder();
//(MediaType.parse("image/png"), new File("/mnt/sdcard/Pictures/0w6d57.png"));
        MultipartBody file = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", "szf.png",
                        RequestBody.create(MediaType.parse("image/png"),
                                new File("/mnt/sdcard/Pictures/0w6d57.png"))).build();
        Request request = builder1.url("http://169.254.112.25/hfs/")
                .post(file)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onResponse: 传输完成。");
            }
        });
    }

    private void load() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient client = builder.connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50, TimeUnit.SECONDS)
                .build();

        Request.Builder builder1 = new Request.Builder();
        Request request = builder1.url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")
                .get().build();

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

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                long l = body.contentLength();
                Message mess = new Message();
                mess.what=222;
                mess.obj=l;
                han.sendMessage(mess);
                is = body.byteStream();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream("/mnt/sdcard/Movies/a12.mp4");
                    int len=0;
                    byte[] arr=new byte[1024];
                    int nlen=0;
                    while( (len=is.read(arr))!=-1){
                        nlen+=len;
                        Message mes = new Message();
                        mes.what=111;
                        mes.arg1=nlen;
                        han.sendMessage(mes);
                        fos.write(arr,0,len);
                    }
                    Log.i(TAG, "onRequestPermissionsResult: "+"下载完毕。");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if( requestCode==222&&grantResults[0]== PackageManager.PERMISSION_GRANTED){

        }
    }

    private void post() {
        //itemid=2&act=ad_app
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient client = builder.readTimeout(1, TimeUnit.MINUTES).connectTimeout(1, TimeUnit.MINUTES)
                .build();
        Request.Builder builder1 = new Request.Builder();
        FormBody.Builder formBody = new FormBody.Builder();
        FormBody formBody1 = formBody.add("itemid", "2").add("act", "ad_app")
                .build();
        Request request = builder1.url(post).post(formBody1).build();

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

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                String string = body.string();
                Log.i(TAG, "post:onResponse: "+string);
            }
        });
    }

    private void get() {
        // TODO 1:创建client对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //数量,单位
        builder.readTimeout(1, TimeUnit.MINUTES);
        builder.connectTimeout(1,TimeUnit.MINUTES);
        OkHttpClient client = builder.build();
        //TODO 2:request对象
        Request.Builder builder1 = new Request.Builder();
        //网址
        builder1.url(get);
        //请求
        builder1.get();
        //设置请求头
//        builder1.header();
        Request request = builder1.build();
        //TODO 3:客户端发送请求
        Call call = client.newCall(request);
        //TODO 4:加入线程池队列得到相应
        call.enqueue(new Callback() {
            //请求失败,打印失败信息
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: "+e.getMessage());
            }
            //请求成功,得到response响应。
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //字符串数据
                ResponseBody body = response.body();
                String string = body.string();//string 只能读取一次。
                Log.i(TAG, "onResponse: string:"+string);
            }
        });
    }
}

对应的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get请求"
        android:id="@+id/main_button_get"
        android:onClick="click"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="post请求"
        android:id="@+id/main_button_post"
        android:onClick="click"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载"
        android:id="@+id/main_button_downLoad"
        android:onClick="click"
        />
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:id="@+id/main_progress"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传"
        android:id="@+id/main_button_upLoad"
        android:onClick="click"
        />

</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值