赞
踩
——Okhttp
【若对该知识点有更多想了解的,欢迎私信博主~~】
在app的 build.gradle中dependencies中添加
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
import android.os.Handler;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpTool {
public static void myPost(final String url, final String json, final NetBack netBack) {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
//构造RequestBody:携带要填充的数据 以及 数据格式
RequestBody body = RequestBody.create(
MediaType.parse("application/json;charset=utf-8"), json
);
//构造Request请求对象:url()--请求的地址,post()--post方法,默认get方法
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//构造OkHttpClient发起请求:newCall()--发起请求
//并构造Response接收返回结果:execute()--执行接收
Response response = new OkHttpClient()
.newCall(request)
.execute();
//获取Response返回的内容
final String rjson = response.body().string();
//返回结果
handler.post(new Runnable() {
@Override
public void run() {
netBack.OnSuccess(rjson);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public interface NetBack {
void OnSuccess(String rjson);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。