安卓开发之okHttp请求封装
【代码】安卓开发之okHttp请求封装。只封装了get和post请求
·
package util;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class NetWork {
private static String userAgent = System.getProperty("http.agent");
//定义请求基础地址
public static final String BASEURL = "你的基础地址";
public static void get(String url, okhttp3.Callback callback) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(BASEURL+url)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
//这个也是get请求,和上个不同的是.removeHeader("User-Agent").addHeader("User-Agent", userAgent)这里,一般是登录的时候要的
public static void getA(String url, okhttp3.Callback callback) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder() //这里写超时设置
.connectTimeout(10, TimeUnit.MINUTES)
.readTimeout(10, TimeUnit.MINUTES) // 读取超时
.writeTimeout(10, TimeUnit.MINUTES) // 写超时
.build();
Request request = new Request.Builder()
.url(BASEURL+url)
.removeHeader("User-Agent")//移除旧的
.addHeader("User-Agent", userAgent)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
//这个post是传json的
public static void postJ(String url, String json, okhttp3.Callback callback) {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = RequestBody
.create(MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url(BASEURL+url)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
//这个post是传formDate的
public static void postF(String url, Map<String, String> map, okhttp3.Callback callback) {
FormBody.Builder builder = new FormBody.Builder();
String userAgent = System.getProperty("http.agent");
for (String key : map.keySet()) {
builder.add(key, map.get(key));
}
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(BASEURL+url)
.post(builder.build())
.build();
okHttpClient.newCall(request).enqueue(callback);
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)