OkHttp3学习

来源:互联网 发布:php 微信自定义分享 编辑:程序博客网 时间:2024/05/23 01:59
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属性
原创粉丝点击