没有合适的资源?快使用搜索试试~ 我知道了~
首页Android中okhttp3使用详解
一、引入包 在项目module下的build.gradle添加okhttp3依赖 compile 'com.squareup.okhttp3:okhttp:3.3.1' 二、基本使用 1、okhttp3 Get 方法 1.1 、okhttp3 同步 Get方法 /** * 同步Get方法 */ private void okHttp_synchronousGet() { new Thread(new Runnable() { @Override public void run() { try { String url = https:/
资源详情
资源评论
资源推荐

Android中中okhttp3使用详解使用详解
一、引入包一、引入包
在项目module下的build.gradle添加okhttp3依赖
compile 'com.squareup.okhttp3:okhttp:3.3.1'
二、基本使用二、基本使用
1、、okhttp3 Get 方法方法
1.1 、、okhttp3 同步同步 Get方法方法
/**
* 同步Get方法
*/
private void okHttp_synchronousGet() {
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "https://api.github.com/";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, response.body().string());
} else {
Log.i(TAG, "okHttp is request error");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Request是okhttp3 的请求对象,Response是okhttp3中的响应。通过response.isSuccessful()判断请求是否成功。
@Contract(pure=true)
public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.
获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;string()适用于获取小数据信息,如果返回的
数据超过1M,建议使用stream()获取返回的数据,因为string() 方法会将整个文档加载到内存中。
@NotNull
public final java.lang.String string()
throws java.io.IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt
to decode the response body as UTF-8.
Throws:
java.io.IOException
当然也可以获取流输出形式;
public final java.io.InputStream byteStream()
1.2 、、okhttp3 异步异步 Get方法方法
有时候需要下载一份文件(比如网络图片),如果文件比较大,整个下载会比较耗时,通常我们会将耗时任务放到工作线程
中,而使用okhttp3异步方法,不需要我们开启工作线程执行网络请求,返回的结果也在工作线程中;
/**
* 异步 Get方法
*/
private void okHttp_asynchronousGet(){
try {
Log.i(TAG,"main thread id is "+Thread.currentThread().getId());
String url = "https://api.github.com/";

















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0