get请求
先写一个工具类装请求体
public class HttpGet {
public static void sendOkHttpRequst(String address,okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
}
在主函数里面回调
HttpPost.okhttpPost("接口", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("error","出错");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Log.d("sucess",data);
}
});
post请求
同get 先写一个工具类
public class HttpPost {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// post
public static void okhttpPost(String url, RequestBody requestBody, okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
}
在主函数里面回调
FormBody.Builder builder = new FormBody.Builder();
builder.add("id",blogId);
FormBody body = builder.build();
HttpPost.okhttpPost("接口", body,new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("error","出错");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Log.d("sucess",data);
}
});
注:ui更新需到主线程里面更新,即使用handler
post更多传参方式请看 https://www.jianshu.com/p/1133389c1f75