Okhttp网络请求使用方法
【摘要】 Okhttp的Github:https://github.com/square/okhttp
导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.5.0'
创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient();
创建请求
Req...
Okhttp的Github:https://github.com/square/okhttp
导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.5.0'
创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient();
创建请求
-
Request request = new Request.Builder()
-
.get()
-
.url("http://某服务器地址/HOME_URL.json")
-
.build();
Call call = okHttpClient.newCall(request);
用enqueue这一个
-
call.enqueue(new okhttp3.Callback() {
-
@Override
-
public void onFailure(okhttp3.Call call, IOException e) {
-
Toast.makeText(getActivity(), "请检查网络连接", Toast.LENGTH_SHORT).show();
-
}
-
-
@Override
-
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
-
Start start = new Gson().fromJson(response.body().string(), Start.class);
-
-
}
-
});
-
}
基本用Okhttp请求就这些
看下具体的代码
-
OkHttpClient okHttpClient = new OkHttpClient();
-
Request request = new Request.Builder()
-
.get()
-
.url("http://某服务器地址/HOME_URL.json")
-
.build();
-
-
okhttp3.Call call = okHttpClient.newCall(request);
-
-
call.enqueue(new okhttp3.Callback() {
-
@Override
-
public void onFailure(okhttp3.Call call, IOException e) {
-
Toast.makeText(getActivity(), "请检查网络连接", Toast.LENGTH_SHORT).show();
-
}
-
-
@Override
-
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
-
Start start = new Gson().fromJson(response.body().string(), Start.class);//这里是解析
-
-
}
-
});
-
}
别忘了加上网络权限 <uses-permission android:name="android.permission.INTERNET"/>
文章来源: blog.csdn.net,作者:第三女神程忆难,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq_40881680/article/details/83691929
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)