Android学习OkHttp笔记(一)

okhttp的github地址:https://github.com/square/okhttp

Okhttp配置

①依赖:implementation 'com.squareup.okhttp3:okhttp:4.8.1'
②添加网络权限:<uses-permission android:name="android.permission.INTERNET"/>

Okhttp使用

1、GET请求

① 获取okHttpClient对象
② 构建Request对象
③ 构建Call对象
④ 通过Call.enqueue(callback)方法来提交异步请求,execute()方法实现同步请求

(1)get 同步请求
//  获取okHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//  构建Request对象
Request request = new Request.Builder().get().url(url).build();
//  构建Call对象
final Call call = okHttpClient.newCall(request);
//  通过execute()方法实现同步请求,要在子线程中执行
new Thread(new Runnable() {
    @Override
    public void run() {
        //同步的方法:阻塞当前线程,所以需要自己去切换线程
        //如果在主线程中进行,会报错,NetworkOnMainThreadException
        //在主线程中进行网络请求异常
        //主线程是ui线程,不允许阻塞
        try {
            Response execute = call.execute();
            Log.d("TAG", execute.body().string());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Error", e.toString());
        }
    }
}).start();
(2)get 异步请求
// 获取okHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
// 构建Request对象
Request request = new Request.Builder().get().url(url).build();
// 构建Call对象
final Call call = okHttpClient.newCall(request);
// 提交异步请求
call.enqueue(new Callback() {
	//请求失败的回调
	@Override
	public void onFailure(@NotNull Call call, @NotNull IOException e) {
		Log.e("Error", e.toString());
	}
	
	//请求成功的回调方法
	//response 响应对象,里面有我们返回来的数据
	//我们想要的东西大部分都在response.body里面
	// response.body().string() 已经将流转换成了字符串
	@Override
	public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
		Log.d("TAG", response.body().string());
	}
});
1、POST请求
(1)post 同步请求
//通过Call.execute()方法实现同步请求
new Thread(new Runnable() {
     @Override
     public void run() {
         try {
             Response execute = call.execute();
             Log.e(TAG, "run: " + execute.body().string());
             //java.lang.IllegalStateException: closed
             //response.body().string()只能使用一次 ??
             //因为使用1次过后,流就关闭了
             //Log.e(TAG, "run: "+string);
         } catch (IOException e) {
             e.printStackTrace();
             Log.e(TAG, "Exception: " + e.toString());
         }
     }
 }).start();
(2)post 异步请求
//获取okHttpClient对象
OkHttpClient build = new OkHttpClient.Builder().build();
 //媒体的类型
 MediaType parse = MediaType.parse("text/x-markdown; charset=utf-8");
 //请求的body,请求体
 RequestBody body = RequestBody.create(parse, "我是一个宝宝");
 Request request = new Request.Builder().post(body).url(post_url).build();
 Call call = build.newCall(request);
 call.enqueue(new Callback() {
     @Override
     public void onFailure(Call call, IOException e) {
         Log.e(TAG, "onFailure: " + e.toString());
     }

     @Override
     public void onResponse(Call call, Response response) throws IOException {
         Log.e(TAG, "onResponse: " + response.body().string());
     }
 });
(3)提交form表单
//onFailure: java.net.UnknownServiceException:
        // CLEARTEXT communication to yun918.cn not permitted by network security policy
        //android 9.0新特性:不支持http请求,只支持https请求
        //怎么就让9.0的手机支持http请求?? 在清单文件中配置就可以了
        //client.newCall(request).enqueue();
        OkHttpClient build = new OkHttpClient.Builder().build();
        //FormBody 是RequestBody的子类
        RequestBody body = new FormBody.Builder()
                .addEncoded("username", "pig")//添加的是form表单的键值对
                .addEncoded("password", "123")
                .addEncoded("phone", "18834071256")
                .addEncoded("verify", "cnmb")
                .build();
        Request request = new Request.Builder().post(body).url(post_form).build();
        build.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: " + e.toString());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse: " + response.body().string());
            }
        });
(4)post 分块请求上传图片
//client.newCall(request).enqueue();
        OkHttpClient build = new OkHttpClient.Builder().build();
        //MultipartBody 是requestbody的子类
        //媒体的类型,application/octet-stream 以二进制形式提交文件
        MediaType type = MediaType.parse("application/octet-stream");
        //sd卡的图片
        File file = new File("/storage/emulated/legacy/Pictures/shous.jpg");
        //文件存在
        if (file.exists()){
            RequestBody requestBody = RequestBody.create(type, file);
            //可以提交多个请求体
            MultipartBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)//key 和file这两个键是固定的
                    .addFormDataPart("key","aaa")//添加第一个请求体,提交上去的图片在哪个目录下存储
                    .addFormDataPart("file","hehe.jpg",requestBody)//添加第二个请求体,需要上传的文件
                    .build();
            Request request = new Request.Builder().post(body).url(post_img).build();
            build.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: "+e.toString());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e(TAG, "onResponse: "+response.body().string());
                }
            });
        }
(5)post 提交流
OkHttpClient build = new OkHttpClient.Builder().build();
        //以流的形式提交参数
        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                //媒体的类型
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }
            /**
             * 以流的形式去写
             * @param sink  输出流
             * @throws IOException
             */
            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.write("This is a difficult problem".getBytes());
            }
        };
        Request request = new Request.Builder().post(body).url(post_url).build();
        build.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse: "+response.body().string());
            }
        });

在这里插入图片描述

参考文档

https://www.jianshu.com/p/24a123ffbee4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值