Android OkHttp 全面详解

Android OkHttp使用和源码详解,GitHub标星1w的安卓架构师必备技能 /创建OkHttpClient对象//创建Request.url(url).build();//创建Call对象client.newCall(request)//通过execute()方法获得请求响应的Response对象@Override@Override//处理UI需要切换到UI线程处理});除了直接 new OkHttpClient 之外,还可以使用内部工厂类 Builder 来设置 OkHttpClient。 阅读详情


目前来说OkHttp已经是对于android开发人员实现网络编程的重要途径之一了。
github地址
这里以3.10.0的源码分析,梳理整个网络请求的流程。

包的导入

引入包

 api 'com.squareup.okhttp3:okhttp:3.10.0'

日志库:搭配更佳

api 'com.squareup.okhttp3:logging-interceptor:3.10.0'

上面的不够好用?来个客户端的日志更清晰的:chuck库

   debugCompile 'com.readystatesoftware.chuck:library:1.1.0'
   releaseCompile 'com.readystatesoftware.chuck:library-no-op:1.1.0'

基本使用

注意网络权限的申请

异步请求

 		OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                //默认get请求
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

同步请求

在android3.0 之后 不允许在主线程里请求网络。
这里可以开启一个子线程去操作同步请求(ps:那还是异步了),或者设置android严苟模式设置。

 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .penaltyDialog()
                .build());

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
           Response response =  okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

build创建

有很多功能可以选择,并不是每个都需要用到的。

		//创建者模式
      OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(60, TimeUnit.SECONDS)//设置连接超时
                //设置读超时
                .readTimeout(60,TimeUnit.SECONDS)
                //设置写超时
                .writeTimeout(60,TimeUnit.SECONDS)
                //添加拦截器 日志库的拦截一般在这里
                .addInterceptor(interceptor)
                //设置网络拦截器
                .addNetworkInterceptor(netInterceptor)
                // 设置dns 解析节点 加快网络访问
                .dns(dns)
                //设置Cookie持久化
                .cookieJar(cookieJar)
                //设置本地缓存策略
                .cache(cache)
                //设置代理
                .proxy(proxy)
                //创建
                .build();

这里说说dns这个,这个是可以设置第三方的dns服务器运营商,加快域名的解析速度。大家知道的dns的解析是一层一层向上传递的查找过程,这个过程可能会耗时。
阿里云有提供第三方的dns服务的,也可以只直接配合OkHttp使用,产品文档

源码跟踪

看了上面的简单使用介绍后,OkHttp的请求操作起点从OkHttpClient.newCall().enqueue() 开始的。

newCall

 @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    // Safely publish the Call instance to the EventListener.
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    //注册到工厂监听类
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
  }

newRealCall方法返回一个RealCall对象,然后会走RealCall.enqueue方法

RealCall.enqueue

 @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    //okhttp  两大核心之一:分发器
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

可以看出来,最后的请求是有Dispatcher的enqueue方法来实现的,Dispatcher是整个OkHttpCient的分发器(调度器),是一种门户模式的实现(不需要关系内部构造,通过门户就可以获取想要的)。主要用来实现执行、取消异步请求、执行请求等操作。

Dispatcher.enqueue

synchronized void enqueue(AsyncCall call) {
	//异步请求队列中数量小于最大请求数 并且 同一主机正运行数量小于最大运行数
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
     //加入队列
     runningAsyncCalls.add(call);
     //执行请求call
      executorService().execute(call);
    } else {
      readyAsyncCalls.add(call);
    }
  }

在Dispatcher的内部维护了一个线程池去执行异步任务,并且会根据一定的策略,保证最大并发个数、同一host主机允许执行请求的线程个数等。
具体看下当前版本的维护情况:

	//
  private int maxRequests = 64;
  private int maxRequestsPerHost = 5;

还维护了三个队列来维护每个请求call,如下:

  /** Ready async calls in the order they'll be run. */  异步等待
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

  /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */ 异步请求中
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

  /** Running synchronous calls. Includes canceled calls that haven't finished yet. */  同步请求中
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

知道了部分参数含义,再来看上面逻辑
如果–》异步请求队列中数量小于最大请求数 并且 同一主机正运行数量小于最大运行线程数
则执行–》 加入异步请求队列中,并执行AsyncCall(AsyncCall实现了Runnable接口,因此整个操作会在子线程中执行)
否则–》
加入异步等待队列

executorService().execute(call)

executorService()是OkHttp线程的创建

 public synchronized ExecutorService executorService() {
    if (executorService == null) {
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
  }

execute(call)方法其实就是执行AsyncCall的run方法。

AsyncCall.execute()

首页自己并没有实现run方法,而是交给NamedRunnable(给线程设置名字)来实现的,会走会自己的execute()方法。

 @Override protected void execute() {
 		//回调标示
      boolean signalledCallback = false;
      try {
      	 //okhttp  两大核心之一:拦截链
        Response response = getResponseWithInterceptorChain();
        //该拦截器从故障中恢复,并根据需要进行重定向。如果呼叫被取消,则可能抛出IOException。
        //判断重定向拦截器是否取消链的下发
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
          //失败回调
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          responseCallback.onResponse(RealCall.this, response);
        }
      } catch (IOException e) {
        if (signalledCallback) {
          // Do not signal the callback twice!
          Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
          eventListener.callFailed(RealCall.this, e);
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }

这里有个非常关键的拦截链。会返回拦截链处理完返回的请求结果Response,并把结果回调回去。所以要看看拦截链到底干啥了。

拦截链

 Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    //client创建加入的自定义拦截器
    interceptors.addAll(client.interceptors());
    //重定向拦截器
    interceptors.add(retryAndFollowUpInterceptor);
    //桥链接拦截器
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    //缓存拦截器
    interceptors.add(new CacheInterceptor(client.internalCache()));
    //连接拦截器
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
    	//client创建加入的自定义网络拦截器
      interceptors.addAll(client.networkInterceptors());
    }
    //请求拦截器
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

这里是典型的责任链模式。为啥了?
这里把所以的拦截器放入interceptors中,最后由RealInterceptorChain来执行proceed方法。来看看内部如何抽象的运行了,因为真正的执行都是各个拦截器处理的。具体看注释。

RealInterceptorChain.proceed()
 public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    //如果我们已经有了一个流,请确认传入的请求将使用它。
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    //如果我们已经有了一个流,请确认这是对chain.proceed()的唯一调用。
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    //创建调用链中的下一个拦截器。 index + 1下一个
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //当前具体拦截器 
    Interceptor interceptor = interceptors.get(index);
    //执行当前拦截器的逻辑,并传入下一个的RealInterceptorChain ,这里会递归执行并返回
    Response response = interceptor.intercept(next);
	//这里返回的已经是 被所有拦截器处理完的结果 
    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    }

    return response;
  }

简要讲讲各个拦截器的作用:

RetryAndFollowUpInterceptor

这个拦截器它的作用主要是负责请求的重定向操作,用于处理网络请求中,请求失败后的重试机制。

  • 会实例化一个StreamAllocation,会创建一个Socket连接对象。
  • 会执行下一个拦截器的实现,并等待返回一个Response对象
  • 协调Connections、Streams、Calls之间的关系
  • 会循环判断是否取消请求,取消则释放相应资源
BridgeInterceptor

这个拦截器它的作用主要负责把用户构造的请求转换为发送给服务器的请求,把服务器返回的响应转换为对用户友好的响应。并对Request中的Head设置默认值,比如Content-Type、Keep-Alive、Cookie等。
执行代码如下:

 @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    RequestBody body = userRequest.body();
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }

      long contentLength = body.contentLength();
      if (contentLength != -1) {
        requestBuilder.header("Content-Length", Long.toString(contentLength));
        requestBuilder.removeHeader("Transfer-Encoding");
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked");
        requestBuilder.removeHeader("Content-Length");
      }
    }
	//默认host
    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
	//添加Keep-Alive默认
    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }

    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    //如果我们添加“Accept-Encoding: gzip”头字段,我们也负责解压传输流
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }
	// 创建OkhttpClient配置的cookieJar
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }
	// 拼接完后执行下一个
    Response networkResponse = chain.proceed(requestBuilder.build());
	//解析服务器返回的Header,如果没有这个cookie,则不进行解析
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }
CacheInerceptor

负责HTTP请求的缓存处理。

  • 根据Request获取当前已有缓存的Response(可能为null),并根据获取到的缓存Response,创建CacheStrategy对象。

CacheInterceptor.intercept()中

//判断是否为空
 Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
//创建CacheStrategy缓存策略
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
  • 通过CacheStrategy判断当前缓存中的Response是否有效(判断是否过期,过期策略自行商量),如果缓存Response可用则直接返回(拦截链终止),否则调用chain.proceed()继续执行下一个拦截器,也就是发送网络请求从服务器获取远端Response。
  //如果缓存无效,且禁止使用网络请求,则直接返回空的Response
    if (networkRequest == null && cacheResponse == null) {
    	//提前返回了
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)//空的
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

    // 缓存在有效期内,则将缓存中的Response返回
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

	//最后如果没有缓存,或者缓存失效,则发送网络请求获取服务器Response
    Response networkResponse = null;
    try {
    //执行下一个拦截器了
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

  • 如果从服务器端成功的获取Response,再判断是否将Response进行缓存处理。
//通过网络请求返回的Response
 Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

//开发人员有设置自定义cache,则将最新的数据缓存起来
    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
ConnectInterceptor

负责建立与服务器地址之间的连接,也就是TCP链接。链接后会进入下一个拦截器

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }
CallServerInterceptor

负责向服务器发送请求,并从服务器拿到远端数据结果。是OkHttp中最核心的网络请求部分。主要是向服务端发送请求数据和获取到数据后构建Response对象。

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    //获取HttpCodec
    HttpCodec httpCodec = realChain.httpStream();
    //RetryAndFollowUpInterceptor创建的StreamAllocation
    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();

    long sentRequestMillis = System.currentTimeMillis();
	//将请求头发送到服务端
    realChain.eventListener().requestHeadersStart(realChain.call());
    httpCodec.writeRequestHeaders(request);
    realChain.eventListener().requestHeadersEnd(realChain.call(), request);
	//如果请求有body,则也发送到服务端
    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
      // Continue" response before transmitting the request body. If we don't get that, return
      // what we did get (such as a 4xx response) without ever transmitting the request body.
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        httpCodec.flushRequest();
        realChain.eventListener().responseHeadersStart(realChain.call());
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      if (responseBuilder == null) {
        // Write the request body if the "Expect: 100-continue" expectation was met.
        realChain.eventListener().requestBodyStart(realChain.call());
        long contentLength = request.body().contentLength();
        CountingSink requestBodyOut =
            new CountingSink(httpCodec.createRequestBody(request, contentLength));
          //请求数据在Okio里面
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
        realChain.eventListener()
            .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
      } else if (!connection.isMultiplexed()) {
        // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
        // from being reused. Otherwise we're still obligated to transmit the request body to
        // leave the connection in a consistent state.
        streamAllocation.noNewStreams();
      }
    }
	//结束网络请求
    httpCodec.finishRequest();
	//从服务端获取相应的数据并构建Response对象
    if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(realChain.call());
      responseBuilder = httpCodec.readResponseHeaders(false);
    }
	//构建响应body
    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

    int code = response.code();
    if (code == 100) {
      // server sent a 100-continue even though we did not request one.
      // try again to read the actual response
      responseBuilder = httpCodec.readResponseHeaders(false);

      response = responseBuilder
              .request(request)
              .handshake(streamAllocation.connection().handshake())
              .sentRequestAtMillis(sentRequestMillis)
              .receivedResponseAtMillis(System.currentTimeMillis())
              .build();

      code = response.code();
    }

    realChain.eventListener()
            .responseHeadersEnd(realChain.call(), response);
	//下面是对响应码的处理
    if (forWebSocket && code == 101) {
      // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
      response = response.newBuilder()
          .body(Util.EMPTY_RESPONSE)
          .build();
    } else {
      response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();
    }

    if ("close".equalsIgnoreCase(response.request().header("Connection"))
        || "close".equalsIgnoreCase(response.header("Connection"))) {
      streamAllocation.noNewStreams();
    }

    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }

    return response;
  }

在CallServerInterceptor中,向服务器发送数据已经获取数据都是一个Okio的框架完成的,这是OkHttp框架的基石。

总结

五个拦截器已经讲完了,拦截器链的执行完毕也是整个请求流程的结束。不必太在意Okio到底怎么实现了,其实更关注中间层的扩展怎么实现就好了。比如cache、cookie、请求进度、失败重请求等中间层功能的扩展。

Okhttp-LoggingInterceptor的简单使用 Okhttp除了提供强大的get,post网络请求外,还包含请求日志的拦截器,可以监视,重写,重试调用请求。1:写一个类,实现接口,复写方法//获取request//request.body转字符串Log.d(//获取response,因为okhttp的原理,response.body在获取一次以后,//就不能再生成响应流了,因此需要构造一个新的返回//将response的数据保存到新的response.string()?//构建新的responseLog.d( 阅读详情

相关推荐

Okhttp3.0 日志拦截器HttpLoggingInterceptor的上传大文件时OutOfMemory以及修复

项目中有使用okhttp+logging-interceptor上传本地保存的log文件, 代码片段: var logLevel = HttpLoggingInterceptor.Level.BODY //默认BODY级别 val builder = OkHttpClient.Builder() //...略 .addInterceptor( HttpLoggingIntercep...

lerous的专栏 3949

Android网络通讯之OkHttp

OkHttp是安卓上常用的网络请求框架,不止可以发送http请求,还可以发送socket请求等。官网地址:https://square.github.io/okhttp/

不积跬步无以至千里,不积小流无以成江海。一个喜欢学习分享的程序员 7707

Android网络请求框架OKHttp的使用详解

本文通过简单明了的示例介绍了如何在Android项目中使用OKHttp进行网络请求。以上代码中,我们在onResponse方法中处理了请求成功的响应数据,在onFailure方法中处理了请求失败的情况。除了发送基本的GET和POST请求,OKHttp还提供了许多其他功能,包括文件上传、文件下载、连接超时设置等。首先,在你的Android项目中的build.gradle文件中添加OKHttp的依赖项。以上代码中,我们使用FormBody.Builder来构建表单数据,并将其作为POST请求的请求体。

TechBurst的博客 1306

[Android]网络框架之OkHttp(详细)(kotlin)

由Square公司贡献的一个处理网络请求的开源项目,是目前Android使用最广泛的网络框架。从Android4.0开始HttpURLConnection的底层实现采用的是OkHttp。OkHttp的介绍,添加依赖,OkHttp的使用get的同步与异步请求post的同步与异步请求POST请求的数据格式POST请求上传文件POST请求上传json对象POST请求上传多个数据OkHttp的配置1.Builder构建器2.自定义拦截器3.自定义缓存4. 自定义Cookie

weixin_63357306的博客 1万+

深入解析STM32定时器中央对齐模式3的双中断机制

本文深入解析了STM32定时器中央对齐模式3的双中断机制。该模式在一个PWM周期内,会在计数器到达ARR(上溢)和0(下溢)时各触发一次更新中断,实现更精细的实时控制。文章详细阐述了其工作原理、配置方法,并指导如何在中断服务函数中通过DIR位区分中断来源,同时探讨了其在电机控制、数字电源等场景下的应用优势与CPU负载挑战。

weixin_29164185的博客 493

CA51F3系列(国产)+低功耗模式

CA51F351P6芯片是基于1T 8051内核的8位微控制器,通常情况下,运行速度比传统的8051芯片快10倍,性能更加优越。内置8K Flash程序存储器,可多次重复编程的特性给用户开发带来了极大的方便。不仅保留了传统8051芯片的基本特性,还集成了12Bit ADC、LCD/LED驱动、Touch Key、16Bit PWM、 UART、RTC、低电压检测(LVD)等功能模块。支持IDLE、STOP和低速运行三种省电模式以适应不同功耗要求的应用。

WANGJIHUIwang的博客 572

Android面试:OkHttp 详解

自定义拦截器允许开发者在请求发送前或响应接收后插入自定义逻辑。@Override// 在发送请求前打印请求信息// 在接收响应后打印响应信息OkHttp 提供了灵活的缓存策略,允许开发者通过自定义缓存策略来控制缓存的行为。默认情况下,OkHttp 使用Cache类来实现缓存功能。但是,开发者也可以通过实现自己的缓存逻辑来替换默认的缓存实现。创建自定义缓存类:实现自己的缓存逻辑,如使用 SQLite 数据库、SharedPreferences 或其他存储方式。

孔乙己大叔的博客 1725

遥感图像融合实战:5分钟搞懂全色与多光谱图像如何提升分辨率(附Python代码)

本文通过实战案例,详细解析了如何利用全色锐化技术融合全色与多光谱遥感图像,以提升图像分辨率。文章深入浅出地介绍了核心概念、环境配置、经典GS融合算法的Python代码实现,并对比了不同算法的优劣,最后提供了效果评估方法与实战陷阱分析,帮助读者快速掌握遥感图像融合的关键技术。

weixin_29041195的博客 394

Android OkHttp详解

Android OkHttp详解 效果图 GET请求             POST请求 OkHttp 首先,我们要先了解一些背景,OkHttp这个框架是有Square公司推出的,进入官网。如果想看API,点击进入API。大概了解了OkHttp之后我们应该知道OkHttp是一个网络框架,学习Android开发的时候接触的HttpURLConnection和Apache提供的Htt

Android开发-CXY的博客 834

OptiSystem仿真:波分与时分复用混合光网络的设计与性能优化

本文详细介绍了如何利用OptiSystem软件设计与优化波分复用与时分复用混合光网络。通过构建四路波分乘以四路时分的系统模型,文章阐述了从信源生成、复用合并、光纤传输到信号解复用与性能评估的全流程,并重点探讨了对抗色散、优化器件参数及探索高级调制格式等核心性能优化策略,为应对未来海量数据需求提供了高效、可行的仿真解决方案。

pink的博客 1106

114.Android简单的动态切换app的图标,两种方式

- 默认的图标-->-- 需要切换的图标-->android:label="短信"-- 默认activity-->

曹二少的博客 5572

android OKHttp的基本使用详解

今天,简单讲讲Android里如何使用OKHttp。   Android框架系列: 一.android EventBus的简单使用 二.android Glide简单使用 三.android OKHttp的基本使用详解   简单说一下学习okhttp的理由 google在Android 6.0中删除了HttpClient的Api,采用的是则是okhttp 高效的使用HTTP,使应...

谢岩的博客 7332

calibre QRC提取寄生参数

typical将上面的文件QCI_flow里面的文件 在Cp 到当前 ,其实应该是某几个文件,但是我给忘记了 就全cp过来了 ,无影响,不过也希望大佬指正。

2202_75711937的博客 1518

Android之OkHttp详解

Android之OkHttp详解文章大纲一、OkHttp简介二、OkHttp简单使用三、OkHttp封装四、项目源码下载 一、OkHttp简介 什么是OkHttp  一般在Java平台上,我们会使用Apache HttpClient作为Http客户端,用于发送 HTTP 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如SSO服务)进行...

weixin_33938733的博客 262

【数据集介绍】MVTec 3D AD数据集介绍

MVTec AD(MVTec Anomaly Detection)数据集是用于异常检测的计算机视觉数据集。该数据集包含来自工业生产中不同材料和产品的图像,包括玻璃、塑料、纺织品等。每个类别都包含正常样本和异常样本。这些异常样本包括各种常见的生产缺陷,如划痕、裂纹、凹陷等。MVTec AD数据集旨在帮助研究人员和从业者开发和评估用于检测工业制造中物体缺陷的算法和系统。

原来也有北瓜 7750

《30天入门 SAP BTP 开发》教程的目录和使用说明,建议收藏

本教程分为两部分:第一部分为SAP BTP入门系列,包含从基础概念到操作步骤的系统性学习内容,建议零基础用户按顺序学习;第二部分为专题文章集合,涵盖SAP BTP的多个技术点,适合已有基础的用户按需查阅。教程包含账号申请、Global Account操作、Java应用开发、AI工具使用等丰富内容,同时解答常见问题并提供实战案例。所有文章均附带详细链接,便于读者系统学习或针对性查阅。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 4393

2024年安卓最新OkHttp3源码详解(五)okhttp连接池复用机制,Android系统面试题

答应大伙的备战金三银四,大厂面试真题来啦!这份资料我从春招开始,就会将各博客、论坛。网站上等优质的Android开发中高级面试题收集起来,然后全网寻找最优的解答方案。每一道面试题都是百分百的大厂面经真题+最优解答。包知识脉络 + 诸多细节。节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。《960全网最全Android开发笔记》《379页Android开发面试宝典》包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。

2401_84545339的博客 1110

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Android-okhttp详解

OkHttp是当下Android使用最频繁的网络请求框架,由Square公司开源。Google在Android4.4以后开始将源码中 的HttpURLConnection底层实现替换为OKHttp,同时现在流行的Retrofit框架底层同样是使用OKHttp的。okhttp的优点是:1,支持Http1、Http2、Quic以及WebSocket2,连接池复用底层TCP(Socket),减少请求延时3,无缝的支持GZIP减少数据流量4,缓存响应数据减少重复的网络请求。

袁震的博客 4044

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

2024年安卓最全Android OkHttp使用和源码详解,中高级Android大厂高频面试题

架构师不是天生的,是在项目中磨练起来的,所以,我们学了技术就需要结合项目进行实战训练,那么在Android里面最常用的架构无外乎 MVC,MVP,MVVM,但是这些思想如果和模块化,层次化,组件化混和在一起,那就不是一件那么简单的事了,我们需要一个真正身经百战的架构师才能讲解透彻其中蕴含的深理。只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。//如果我们被禁止使用网络,并且缓存不足,则失败。

2401_84562210的博客 1106

Android OkHttp的用法详解

OkHttp 是一个高效、灵活的 HTTP 客户端库,在 Android 开发中非常常用。下面介绍如何在 Android 中使用 OkHttp,并附上常见的 GET 和 POST 请求示例。OkHttp如果你还没有添加OkHttp,需要在添加依赖:plaintext123implementation("com.squareup.okhttp3:okhttp:4.12.0") // 最新版如果你用的是(Groovy 语法):plaintext123plaintext1。

XHRK1的博客 1638

android OkHttp 详解

在Android Studio项目中,使用okHttp时要添加: compile 'com.squareup.okhttp:okhttp:2.4.0' OkHttp的使用教程: OkHttpClient mOkHttpClient = new OkHttpClient(); //创建okHttpClient对象 final Request request = new Request.Builder().url("https://baidu.com").build() //创建一个Request对象,设

weixin_42754390的博客 4200

android okhttp异步请求使用详解 (2),安卓面试题及答案2020

联网请求文本数据 大文件下载上传 请求图片 二、okhttp基本使用 ======================================================================= 1.发起get异步请求 布局文件很简单,只有几个按钮 public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity "; private...

m0_66145060的博客 235

android okhttp封装步骤,Android OkHttp的简单使用和封装详解

Android OkHttp的简单使用和封装详解1,昨天把okHttp仔细的看了一下,以前都是调用同事封装好了的网络框架,直接使用很容易,但自己封装却不是那么简单,还好,今天就来自我救赎一把,就和大家写写从最基础的OKHttp的简单get、post的使用,再到它的封装。2,OkHttp的简单使用首先我们创建一个工程,并在布局文件中添加三个控件,TextView(用于展示获取到json后的信息)、B...

weixin_39615643的博客 426

Android中okhttp原理详解

目录 1、okhttp工作的大致流程2、okhttp中的连接3、Dispatcher和线程池4、OkHttp中的设计模式5、OkHttp的优势6、参考连接1、okhttp工作的大致流程 1...

Android技术之家 2864
上一篇: android 9.0 activity启动流程分析
下一篇: android Context家族及详解
HUandroid
博客等级 码龄10年 35粉丝 113原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值