okhttp3使用
来源:互联网 发布:淘宝代购打折 编辑:程序博客网 时间:2024/06/02 07:31
学习了OkHttp3,记录一下用过的方法;
GET网络请求:
OkHttpClient mOkHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url("http://www.baidu.com") .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, response.body().string()); } });
- 创建
OkHttpClient
对象,可以直接new,也可以使用OkHttpClient.Builder
来创建,前者创建使用默认设置,后者可以定义连接时间,读取时间等。 - 创建
Request
对象,通过Request.Builder
来创建。 mOkHttpClient.newCall(request)
获取Call
对象。call.enqueue()
异步请求,设置回调。
当然也可以发送同步请求(当然不能再主线程中):
Response response = mOkHttpClient.newCall(request).execute();
Post请求:
OkHttpClient mOkHttpClient = new OkHttpClient(); FormBody formBody = new FormBody.Builder() .add("string1", "param1") .build(); Request request = new Request.Builder() .url("url") .post(formBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, response.body().string()); } });
Post请求可以创建FormBody
对象,添加一些数据,然后在创建Request
的时候添加FormBody
对象。 这是Post的基本使用。
Post上传文件:
我自己在tomcat上跑一个servlet,获取并保存客户端传来的文件。
先看Android的代码:
private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text;charset=UTF-8"); OkHttpClient mOkHttpClient = new OkHttpClient(); File file = new File("sdcard/Android/myText"); RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, file); Request request = new Request.Builder() .url("http://10.0.2.2:8080/PostServer/pac.PostServer") .post(requestBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.i(TAG, e.getMessage(), e); } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, response.body().string()); } });
将sd卡下的文件上传, 和一般post请求不同点:
MediaType.parse
设置类型。
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, file);
创建RequestBody对象,添加文件对象。
Request.Builder
对象的post方法添加RequestBod
对象到Request
中。
最后发送请求。
因为Callback
的onResponse
方法的参数Response
,调用
response.body().byteStream()
可以获得输入流,所以okhttp
处理数据较多网络请求还是很好的。
0 0
- okhttp3使用
- okhttp3使用
- okhttp3使用
- okhttp3使用
- okhttp3的简单使用
- 浅析 - okHttp3使用总结
- okhttp3的使用
- Retrofit2+okhttp3 使用教程
- OkHttp3使用详解
- OkHttp3使用详解
- OkHttp3 如何使用
- OkHttp3的使用
- okhttp3使用详解
- OkHttp3使用详解
- Android OKhttp3使用
- okhttp3使用总结
- Retrofit2、okHttp3、RxAndroid使用
- okHttp3的简单使用
- 序列化和反序列化
- iOS_Json字符串转字典、字典转成Json字符串
- JAVA WEB从入门到精通day04 javascript学习(2)
- 正则表达式
- 正则表达式分组、断言详解
- okhttp3使用
- Android路由实现
- 操作手册和用户手册的区别
- C 语言高精度算法(一)——加法
- [LeetCode]30. Substring with Concatenation of All Words
- Brief Introduction to Shaders Using GLSL shader最详解
- Leetcode 451 Sort Characters By Frequency
- BAT文件语法和技巧(bat文件的编写及使用)
- elasticsearch