okhttp之Request

转载请以链接形式标明出处:
本文出自:103style的博客


base on 3.12.0


目录

  • Request 简介
  • Request相关的配置方法
  • Header介绍

Request 简介

Request即我们构建的每一个HTTP请求。通过配置请求的 地址http方法请求头 等信息。

使用方法:

Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")//指定请求地址
        .delete()//指定请求的方法
        .build();

Request成员变量和构造方法:

public final class Request {
    final HttpUrl url;//请求地址
    final String method;//请求方法
    final Headers headers;//头信息
    final @Nullable RequestBody body;//请求体
    //当前请求的标签
    final Map<Class<?>, Object> tags;
    // 头信息的Cache-Control
    private volatile @Nullable CacheControl cacheControl; 

    Request(Builder builder) {
        this.url = builder.url;
        this.method = builder.method;
        this.headers = builder.headers.build();
        this.body = builder.body;
        this.tags = Util.immutableMap(builder.tags);
    }
    ...
}

Request相关的配置方法

默认的配置,默认为get请求.

public Builder() {
    this.method = "GET";
    this.headers = new Headers.Builder();
}
  • 设置请求地址 .url(xxx)

      public Builder url(HttpUrl url) {
          if (url == null) throw new NullPointerException("url == null");
          this.url = url;
          return this;
      }
      public Builder url(String url) {
          if (url == null) throw new NullPointerException("url == null");
    
          // Silently replace web socket URLs with HTTP URLs.
          if (url.regionMatches(true, 0, "ws:", 0, 3)) {
              url = "http:" + url.substring(3);
          } else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
              url = "https:" + url.substring(4);
          }
    
          return url(HttpUrl.get(url));
      }
      public Builder url(URL url) {
          if (url == null) throw new NullPointerException("url == null");
          return url(HttpUrl.get(url.toString()));
      }
    
  • 设置http请求方法

    • .get()
    • .head()
    • .post(RequestBody body)
    • .delete(@Nullable RequestBody body)
    • .delete()
    • .put(RequestBody body)
    • .patch(RequestBody body)
    • .method(String method, @Nullable RequestBody body)
  • 设置http请求的标签

    • tag(@Nullable Object tag)
    • tag(Class<? super T> type, @Nullable T tag)
  • 设置http请求header中的Cache-Contro

    • cacheControl(CacheControl cacheControl)
      设置此请求的Cache-Contro,替换所有已经存在的缓存控制标头。 如果为null,这将清除此请求的缓存控制标头。

Header介绍

Headerhttp请求的头信息,通过以下代码我们知道header是由一个 字符串数组 组成的。

public final class Headers {
  private final String[] namesAndValues;
  Headers(Builder builder) {
    this.namesAndValues = builder.namesAndValues.toArray(new String[builder.namesAndValues.size()]);
  }
  private Headers(String[] namesAndValues) {
    this.namesAndValues = namesAndValues;
  }
  ...
}
  • 添加头信息的方法:
    我们通过.add("Connection:Keep-Alive")实际上时是吧Connection:KeepKeep-Alive依次添加到这个保存头信息的字符串数组中。

    public Builder add(String line) {
        int index = line.indexOf(":");
        if (index == -1) {
            throw new IllegalArgumentException("Unexpected header: " + line);
        }
        return add(line.substring(0, index).trim(), line.substring(index + 1));
    }
    public Builder add(String name, String value) {
        checkName(name);
        checkValue(value, name);
        return addLenient(name, value);
    }
    Builder addLenient(String name, String value) {
        namesAndValues.add(name);
        namesAndValues.add(value.trim());
        return this;
    }
    
  • 获取头信息的方法:
    通过比较单数位的值,来获取对应索引的下一个索引的值。

    public String get(String name) {
        for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) {
            if (name.equalsIgnoreCase(namesAndValues.get(i))) {
                return namesAndValues.get(i + 1);
            }
        }
        return null;
    }
    
  • 删除头信息的方法:
    依次删除单数位的值,相同此索引和下一索引的值。

    public Builder removeAll(String name) {
        for (int i = 0; i < namesAndValues.size(); i += 2) {
            if (name.equalsIgnoreCase(namesAndValues.get(i))) {
                namesAndValues.remove(i); // name
                namesAndValues.remove(i); // value
                i -= 2;
            }
        }
        return this;
    }
    
  • 修改头信息的方法:
    先删除对应的头信息,再添加进数组。

    public Builder set(String name, String value) {
          (name);
        checkValue(value, name);
        removeAll(name);
        addLenient(name, value);
        return this;
    }
    

以上

package com.zhy.http.okhttp; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import com.zhy.http.okhttp.cookie.SimpleCookieJar; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Response; import com.zhy.http.okhttp.builder.GetBuilder; import com.zhy.http.okhttp.builder.PostFileBuilder; import com.zhy.http.okhttp.builder.PostFormBuilder; import com.zhy.http.okhttp.builder.PostStringBuilder; import com.zhy.http.okhttp.callback.Callback; import com.zhy.http.okhttp.https.HttpsUtils; import com.zhy.http.okhttp.request.RequestCall; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * Created by zhy on 15/8/17. */ public class OkHttpUtils { public static final String TAG = "OkHttpUtils"; public static final long DEFAULT_MILLISECONDS = 10000; private static OkHttpUtils mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private OkHttpUtils() { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); //cookie enabled okHttpClientBuilder.cookieJar(new SimpleCookieJar()); mDelivery = new Handler(Looper.getMainLooper()); if (true) { okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } mOkHttpClient = okHttpClientBuilder.build(); } private boolean debug; private String tag; public OkHttpUtils debug(String tag) { debug = true; this.tag = tag; return this; } public static OkHttpUtils getInstance() { if (mInstance == null) { synchronized (OkHttpUtils.class) { if (mInstance == null) { mInstance = new OkHttpUtils(); } } } return mInstance; } public Handler getDelivery() { return mDelivery; } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } public static GetBuilder get() { return new GetBuilder(); } public static PostStringBuilder postString() { return new PostStringBuilder(); } public static PostFileBuilder postFile() { return new PostFileBuilder(); } public static PostFormBuilder post() { return new PostFormBuilder(); } public void execute(final RequestCall requestCall, Callback callback) { if (debug) { if(TextUtils.isEmpty(tag)) { tag = TAG; } Log.d(tag, "{method:" + requestCall.getRequest().method() + ", detail:" + requestCall.getOkHttpRequest().toString() + "}"); } if (callback == null) callback = Callback.CALLBACK_DEFAULT; final Callback finalCallback = callback; requestCall.getCall().enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { sendFailResultCallback(call, e, finalCallback); } @Override public void onResponse(final Call call, final Response response) { if (response.code() >= 400 && response.code() <= 599) { try { sendFailResultCallback(call, new RuntimeException(response.body().string()), finalCallback); } catch (IOException e) { e.printStackTrace(); } return; } try { Object o = finalCallback.parseNetworkResponse(response); sendSuccessResultCallback(o, finalCallback); } catch (Exception e) { sendFailResultCallback(call, e, finalCallback); } } }); } public void sendFailResultCallback(final Call call, final Exception e, final Callback callback) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onError(call, e); callback.onAfter(); } }); } public void sendSuccessResultCallback(final Object object, final Callback callback) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onResponse(object); callback.onAfter(); } }); } public void cancelTag(Object tag) { for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } public void setCertificates(InputStream... certificates) { mOkHttpClient = getOkHttpClient().newBuilder() .sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, null, null)) .build(); } public void setConnectTimeout(int timeout, TimeUnit units) { mOkHttpClient = getOkHttpClient().newBuilder() .connectTimeout(timeout, units) .build(); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值