android网络框架之OkHttp
一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary)
用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,现在已经打不出来)
优势
允许连接到同一个主机地址的所有请求,提高请求效率
共享Socket,减少对服务器的请求次数
通过连接池,减少了请求延迟
缓存响应数据来减少重复的网络请求
减少了对数据流量的消耗
自动处理GZip压缩
官网
OkHttp官网地址:http://square.github.io/okhttp/
OkHttp GitHub地址:https://github.com/square/okhttp
导依赖
implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
代码
public class MainActivity extends AppCompatActivity {
Button btn, enroll;
ImageView img;
ProgressBar progressBar;
private static final int MAX = 100;
private static final int CURRENT = 101;
private static final int FINISH = 103;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MAX) {
progressBar.setMax((Integer) msg.obj);
} else if (msg.what == CURRENT) {
progressBar.setProgress(progressBar.getProgress() + (int) msg.obj);
} else if (msg.what == FINISH) {
Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/Pictures/marry.jpg");
img.setImageBitmap(bitmap);
} else if (msg.what == 2001) {
Toast.makeText(MainActivity.this, "" + msg.obj, Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.pro_bar);
btn = findViewById(R.id.download);
img = findViewById(R.id.img);
enroll = findViewById(R.id.enroll);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downloadImage();
}
});
enroll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postEnroll();
}
});
}
private void downloadImage() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.callTimeout(5, TimeUnit.SECONDS);
builder.connectTimeout(5, TimeUnit.SECONDS);
builder.readTimeout(5, TimeUnit.SECONDS);
OkHttpClient client = builder.build();
Request.Builder builder1 = new Request.Builder();
builder1.get();
builder1.url("http://10.211.55.4/hfs_demo/g.jpg");
Request request = builder1.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//失败
@Override
public void onFailure(Call call, IOException e) {
}
//连接
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
int l = (int) body.contentLength();
Message obtain = Message.obtain();
obtain.what = MAX;
obtain.obj = l;
handler.sendMessage(obtain);
InputStream inputStream = body.byteStream();
FileOutputStream fos = new FileOutputStream("/sdcard/Pictures/marry.jpg");
int len = 0;
byte[] b = new byte[1024 * 8];
while ((len = inputStream.read(b)) != -1) {
fos.write(b, 0, len);
Message obtain1 = Message.obtain();
obtain1.what = CURRENT;
obtain1.obj = len;
handler.sendMessage(obtain1);
}
handler.sendEmptyMessage(FINISH);
inputStream.close();
fos.close();
}
});
}
private void postEnroll() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(5, TimeUnit.SECONDS);
builder.connectTimeout(5, TimeUnit.SECONDS);
builder.callTimeout(5, TimeUnit.SECONDS);
Request.Builder builder1 = new Request.Builder();
OkHttpClient client = builder.build();
FormBody formBody = new FormBody.Builder().add("phone", "18360178825")
.add("passwd", "12345").build();
builder1.post(formBody);
builder1.url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&");
Request request = builder1.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
String string = body.string();
Message obtain = Message.obtain();
obtain.what = 2001;
obtain.obj = string;
handler.sendMessage(obtain);
}
});
}
}