1.原生okhttp
- 主要功能
1、联网请求文本数据
2、大文件下载
3、大文件上传
4、请求图片
- 下载地址
jar包: http://square.github.io/okhttp/
github:https://github.com/square/okhttp
- get请求
OkHttpClient client = new OkHttpClient();
//要在子线程执行
private String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
- post请求
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Okhttp第三方封装好的库 Okhttp-utils
String url = "http://www.csdn.net/";
OkHttpUtils
.get()
.url(url)
.addParams("username", "hyman")
.addParams("password", "123")
.build()
.execute(new StringCallback()
{
@Override
public void onError(Request request, Exception e)
{
}
@Override
public void onResponse(String response)
{
}
});
- post请求
OkHttpUtils
.post()
.url(url)
.addParams("username", "hyman")
.addParams("password", "123")
.build()
.execute(callback);
- 文件下载
OkHttpUtils//
.get()//
.url(url)//
.build()//
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "gson-2.2.1.jar")//
{
@Override
public void inProgress(float progress)
{
mProgressBar.setProgress((int) (100 * progress));
}
@Override
public void onError(Request request, Exception e)
{
Log.e(TAG, "onError :" + e.getMessage());
}
@Override
public void onResponse(File file)
{
Log.e(TAG, "onResponse :" + file.getAbsolutePath());
}
});
- 文件上传
OkHttpUtils.post()//
.addFile("mFile", "messenger_01.png", file)//
.addFile("mFile", "test1.txt", file2)//
.url(url)
.params(params)//
.headers(headers)//
.build()//
.execute(new MyStringCallback());
- 请求图片
OkHttpUtils
.get()//
.url(url)//
.build()//
.execute(new BitmapCallback()
{
@Override
public void onError(Request request, Exception e)
{
mTv.setText("onError:" + e.getMessage());
}
@Override
public void onResponse(Bitmap bitmap)
{
mImageView.setImageBitmap(bitmap);
}
});
注:请求列表图片时不建议使用
3.其他Okhttp封装的库
下载地址:https://github.com/jeasonlzy/okhttp-OkGo
里面封装了很多功能