注册

Android三方库OKHTTP请求的使用

okhttp

Okhttp是网络请求框架。OkHttp主要有Get请求、Post请求等功能。
使用前,需要添加依赖,在当前项目的build.gradle下加入以下代码:

implementation 'com.squareup.okhttp3:okhttp:3.5.0'

Okhttp的Get请求
使用OkHttp进行Get请求只需要完成以下四步:

获取OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();

构造Request对象
Request request = new Request.Builder() .get() .url("https://v0.yiketianqi.com/api?version=v62&appid=12646748&appsecret=SLB1jIr8&city=北京") .build();

将Request封装为Call
Call call = okHttpClient.newCall(request);

根据需要调用同步或者异步请求方法
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();

//异步调用,并设置回调函数
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() {
textView.setText(res);
}
});
}
});



OkHttp进行Post请求
使用OkHttp进行Post请求和进行Get请求很类似,只需要以下五步:

获取OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
1
构建FormBody或RequestBody或构架我们自己的RequestBody,传入参数

//OkHttp进行Post请求提交键值对
FormBody formBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "admin")
.build();

//OkHttp进行Post请求提交字符串
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");

//OkHttp进行Post请求上传文件
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);
}

//OkHttp进行Post请求提交表单
File file = new File(Environment.getExternalStorageDirectory(), "1.png");
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", RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
构建Request,将FormBody作为Post方法的参数传入
final Request request = new Request.Builder()
.url("http://www.jianshu.com/")
.post(formBody)
.build();

将Request封装为Call
Call call = okHttpClient.newCall(request);
1
调用请求,重写回调方法
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() {
textView.setText(res);
}
});
}
});


————————————————
版权声明:本文为CSDN博主「maisomgan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45828419/article/details/115632155

1 个评论

学到了

要回复文章请先登录注册