本文主要是介绍OkHttp3学习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
OkHttp3学习之旅:1、OkHttp3会从很多常见的连接问题中自动恢复,
如果你的服务器配置了多个IP地址,当第一个IP连接失败时,会自动尝试下一个IP
OKHttp3使用前需在build.gradle里面配置以下内容:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okio:okio:1.7.0'
2、okhttp3已经没有FormEncodingBuilder,可用FormBody.Builder代替
异步POST请求:
OkHttpClient okHttpClient = new OkHttpClient();
//请求参数封装
RequestBody body = new FormBody.Builder()
.add("cmd","BannerLists")
.add("position","index")
.add("place","3")
.build();
//请求封装
final Request request = new Request.Builder()
.url(UrlUtils.newBanner)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Main2Activity.this,"请求失败",Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//请求返回的数据为response.body().string()
String result = response.body().string();
LogUtils.i("wanlijun","result="+result);
//回调不在UI线程,需进入UI线程才能弹Toast
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main2Activity.this,"请求成功",Toast.LENGTH_LONG).show();
}
});
}
});
3、Picasso加载网络图片:
build.gradle里面配置:compile 'com.squareup.picasso:picasso:2.5.2'
用法:Picasso.with(context)
.load(url)
.placeholder(R.drawable.default)
.error(R.drawable.error)
.into(imageView);
4、当xml布局的根布局LinearLayout没有设置orientation属性,根布局里面的子布局将不生效,不显示
并且运行不会报错,也不会提示,所以一定要记得给LinearLayout设置orientation属性
这篇关于OkHttp3学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!