OkHttp是一个优秀的网络请求框架,主要介绍介绍OkHttp的Get请求、Post请求、上传下载文件、 上传下载图片等功能。
1、进行依赖配置和xml中加入联网权限
在对应的Module的gradle中添加
compile 'com.squareup.okhttp3:okhttp:3.5.0'
然后同步一下项目即可
同时需要在AndroidMainffest.xml中加入联网的权限
<uses-permission android:name="android.permission.INTERNET" />
- OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url("https:www.baidu.com")
.build();
如果我们需要在get请求时传递参数,我们可以以下面的方式将参数拼接在url之后
https:www.baidu.com?username=admin&password=admin
Call call = client.newCall(request);
同步调用,返回Response,会抛出IO异常
同步调用会阻塞主线程,一般不适用
Response response = call.execute();
异步调用,并设置回调函数
异步调用的回调函数是在子线程,我们不能在子线程更新UI,
需要借助于runOnUiThread()方法或者Handler来处理
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
- OkHttpClient client = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "admin")
.build();
final Request request = new Request.Builder()
.url("http://www.jianshu.com/")
这里的rul可以是别的设置好的string格式的地址
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
//创建一个OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建一个RequestBody,即需要传输的json放入request中进行传输
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),json);
//创建一个请求对象
Request request = new Request.Builder()
.url(url_data)
.post(requestBody)
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
..
}
@Override
public void onResponse(Call call, Response response) throws IOException {
..
}
});
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
if (!file.exists()){
Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
}else{
RequestBody requestBody2 = RequestBody.create(MediaType.parse("application/octet-stream"), file);
代码中的application/octet-stream表示文件是任意二进制数据流,当然也可以换成更具体的image/png
}
同时注意需要在xml文件中添加权限代码:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
compile 'com.squareup.okio:okio:1.11.0'
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
/也可以在这里定义好filepath到时候直接在下面的代码中传入
if (!file.exists()){
Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
RequestBody muiltipartBody = new MultipartBody.Builder()
/如果提交的是表单一定要设置这句
.setType(MultipartBody.FORM)
.addFormDataPart("username", "admin")/第一个双引号是键值对的键,第二个是值
.addFormDataPart("password", "admin")/第一个双引号是键值对的键,第二个是值
.addFormDataPart("myfile", "1.png", /第二个参数这里可以换成设置好的路径filepath如下行代码所示/ RequestBody.create(MediaType.parse("application/octet-stream"), file))
/.addFormDataPart("myfile", filepath,RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();