Android OKHttp介绍与使用(一)_网络请求

为什么使用OKHttp

1、之前Android的网络请求传统的方式是使用HttpUrlConnection和HttpClient(冗余代码也比较多),但这两种方式使用起来比较麻烦,需要自己再次封装。更重要的一点是Android 6.0已经不支持HttpClient了,并且早在Android 4.4的源码中HttpUrlConnection已经被替换成okHttp了。
2、okHttp是一个轻量级的网络请求框架。
3、支持一般的get、post请求;支持基于http的文件上传与下载;支持session保持等。
4、OKHttp的使用需要依赖OKIO

简单使用Demo

AndroidStudio需要添加这两个:
​​​compile 'com.squareup.okio:okio:1.9.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'​
​​
如下:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.squareup.okio:okio:1.9.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'

OkHttp使用方法:

new OkHttpClient();
mRequest=new Request.Builder().get().url(imgurl).build();
mOKHttpClient.newCall(mRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){

}

}
});

图片Demo代码

点击按钮进行网络请求,注意在manifest里面添加网络请求权限

public class MainActivity extends AppCompatActivity
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==0x11){
byte[] bytes=(byte[]) msg.obj;
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
mImageView.setImageBitmap(bitmap);

}
}
};
private ImageView mImageView;
private Button mButton;
private OkHttpClient mOKHttpClient;
private Request mRequest;
private String imgurl="http://www.ld12.com/upimg358/allimg/c150111/142096112145N0-21106.jpg";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView= (ImageView) findViewById(R.id.iamgeview);
mButton= (Button) findViewById(R.id.button);
mOKHttpClient=new OkHttpClient();
mRequest=new Request.Builder().get().url(imgurl).build();
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mOKHttpClient.newCall(mRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(getApplicationContext(),e.toString()+"",Toast.LENGTH_SHORT).show();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
Message message=new Message();
message.what=0x11;
message.obj=response.body().bytes();
mHandler.sendMessage(message);
}

}
});
}
});
}


}