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);
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐