OkHttp3

    xiaoxiao2021-03-25  60

    OkHttp3

    <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.2.0</version> </dependency>

    步骤:

    创建OkHttpClient客户端(dns、cookies、拦截器、连接池、代理、SSL)构建请求对象(url、addHeader、post、method)客户端获得调用对象调用对象选择执行方式(判断是否关闭、是否已执行) // 创建okHttpClient对象 OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build(); // 不同方式构建请求主体 RequestBody body = new FormBody.Builder().add("haha", "ss").build(); // 构建请求 final Request request = new Request.Builder().url( "http://www.baidu.com").post(body).build(); // cacheControl = 缓存设置 // 生成调用对象 Call call = mOkHttpClient.newCall(request); // isCanceled = 是否已经关闭 isExecuted = 是否执行 // 执行异步请求 call.enqueue(new Callback() { public void onResponse(Call call, Response response) throws IOException { System.out.println("haha1"); } public void onFailure(Call call, IOException e) { System.out.println("haha2"); } }); // 执行同步 // call.execute();

    cookies 操作

    // 获得客户端 new OkHttpClient.Builder() // 使用cookies .cookieJar(new CookieJar() { // cookies存储 List<Cookie> cookies = new ArrayList<Cookie>(); // 保存相应cookies public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { for (Cookie cookie : cookies) { System.out.println(cookie.name() + "--" + cookie.value()); } } // 请求加载客户端 public List<Cookie> loadForRequest(HttpUrl url) { return cookies; } }).build();
    转载请注明原文地址: https://ju.6miu.com/read-36363.html

    最新回复(0)