okhttp详解(参数)

OkHttpClient client=new OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
    .writeTimeout(60,TimeUnit.SECONDS)          //设置写超时
    .retryOnConnectionFailure(true)             //是否自动重连
    .build();                                   //构建OkHttpClient对象

retryOnConnectionFailure: 
当遇到连接问题时配置此客户端重试或者不重试

//================================
添加网络拦截器:

第一步:(预编译)

compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'

定义拦截工具:
public class HttpLogger implements HttpLoggingInterceptor.Logger {
    @Override
    public void log(String message) {
        Log.d("HttpLogInfo", message);
    }

添加拦截事件:
HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        mOkHttpClient = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .addNetworkInterceptor(logInterceptor)
            .build();
     --------------------------------------------------

    addNetworkInterceptor--->http://www.jianshu.com/p/e044cab4f530
    HttpLoggingInterceptor.level.BASIC;// 记录请求和响应行。
    HttpLoggingInterceptor.level.BODY;// 记录请求和响应行及其各自的标题和正文(如果存在)。
    HttpLoggingInterceptor.level.HEADERS;// 记录请求和响应行及其相应的标题
    HttpLoggingInterceptor.level.NONE;// 没有日志

在给OkhttpClient添加网络请求拦截器的时候需要注意,应该调用方法addNetworkInterceptor,而不是addInterceptor。因为有时候可能会通过cookieJar在header里面去添加一些持久化的cookie或者session信息。这样就在请求头里面就不会打印出这些信息。

注意:
okHttp2.7用的是new FormEncodingBuilder(),而OkHttp3.x用的是FormBody.Builder();

OkHttp MediaType的使用:

public static final MediaType MEDIA_TYPE_MARKDOWN  = MediaType.parse("text/x-markdown; charset=utf-8");

属性: 
text/html : HTML格式
text/plain :纯文本格式      
text/xml :  XML格式
image/gif :gif图片格式    
image/jpeg :jpg图片格式 
image/png:png图片格式
以application开头的媒体格式类型:

application/xhtml+xml :XHTML格式
application/xml     : XML数据格式
application/atom+xml  :Atom XML聚合格式    
application/json    : JSON数据格式
application/pdf       :pdf格式  
application/msword  : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

另外一种常见的媒体格式是上传文件之时使用的:
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
注意:MediaType.parse("image/png")里的"image/png"不知道该填什么,可以参考---》http://www.w3school.com.cn/media/media_mimeref.asp
如何使用呢?(在请求体里面写入类型和需要写入的数据,通过post请求)
String body = "hdsoifhjoihdsfh";
RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, body);

下面对应okhttp,还有两种requestBody,一个是FormBody,一个是MultipartBody

RequestBody的使用:

// 提交一个表单
RequestBody formBody = new FormBody.Builder()
        .add("gid", "2592154")
        .add("rid", "32214405")
        .build();

// 通过流的方式
RequestBody requestBody = new RequestBody() {
      // 请求的类型
      @Override 
      public MediaType contentType() {
        return MEDIA_TYPE_MARKDOWN;
      }

      // 写出 请求的内容
      @Override 
      public void writeTo(BufferedSink sink) throws IOException {
        sink.writeUtf8("Numbers\n");
        sink.writeUtf8("-------\n");
        for (int i = 2; i <= 997; i++) {
          sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
        }
      }

      // 通过运算写入的数据
      private String factor(int n) {
        for (int i = 2; i < n; i++) {
          int x = n / i;
          if (x * i == n) return factor(x) + " × " + i;
        }
        return Integer.toString(n);
      }

// 分块请求
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();

请求头的设置:

Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .addHeader("Accept", "application/vnd.github.v3+json")
        .build();

 以下就是一个典型的POST请求:
    POST / HTTP/1.1
    Host: www.baidu.com
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)
    Gecko/20050225 Firefox/1.0.1
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 40
    Connection: Keep-Alive
    Accept-Language: ZH

请求头的参数详情:http://blog.csdn.net/zadarrien_china/article/details/53422785

请求的是json格式post解析:

post请求提body的添加
final JSONObject reJson = new JSONObject();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 RequestBody formBody = RequestBody.create(JSON, String.valueOf(reJson));

Builder里面的参数:

final Dispatcher dispatcher;  //分发器
final Proxy proxy;  //代理
final List<Protocol> protocols; //协议
final List<ConnectionSpec> connectionSpecs; //传输层版本和连接协议
final List<Interceptor> interceptors; //拦截器
final List<Interceptor> networkInterceptors; //网络拦截器
final ProxySelector proxySelector; //代理选择
final CookieJar cookieJar; //cookie
final Cache cache; //缓存
final InternalCache internalCache;  //内部缓存
final SocketFactory socketFactory;  //socket 工厂
final SSLSocketFactory sslSocketFactory; //安全套接层socket 工厂,用于HTTPS
final CertificateChainCleaner certificateChainCleaner; // 验证确认响应证书 适用 HTTPS 请求连接的主机名。
final HostnameVerifier hostnameVerifier;    //  主机名字确认
final CertificatePinner certificatePinner;  //  证书链
final Authenticator proxyAuthenticator;     //代理身份验证
final Authenticator authenticator;      // 本地身份验证
final ConnectionPool connectionPool;    //连接池,复用连接
final Dns dns;  //域名
final boolean followSslRedirects;  //安全套接层重定向
final boolean followRedirects;  //本地重定向
final boolean retryOnConnectionFailure; //重试连接失败
final int connectTimeout;    //连接超时
final int readTimeout; //read 超时
final int writeTimeout; //write 超时

如果不设置,了解下面的默认设置:

         dispatcher = new Dispatcher();
        protocols = DEFAULT_PROTOCOLS;
        connectionSpecs = DEFAULT_CONNECTION_SPECS;
        proxySelector = ProxySelector.getDefault();
        cookieJar = CookieJar.NO_COOKIES;
        socketFactory = SocketFactory.getDefault();
        hostnameVerifier = OkHostnameVerifier.INSTANCE;
        certificatePinner = CertificatePinner.DEFAULT;
        proxyAuthenticator = Authenticator.NONE;
        authenticator = Authenticator.NONE;
        connectionPool = new ConnectionPool();
        dns = Dns.SYSTEM;
        followSslRedirects = true;
        followRedirects = true;
        retryOnConnectionFailure = true;
        connectTimeout = 10_000;
        readTimeout = 10_000;
        writeTimeout = 10_000;
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值