OkHttp使用教程

「okhttp3 4.9.3 版本简单解析」 「okhttp3 4.9.3 版本简单解析」 一、写在前面 关于okhttp3的解析网上已经有非常多优秀的博文了,每每看完都觉得醍醐灌顶,豁然开朗。但等不了几天再回头看,还是跟当初一样陌生,究其根本原因,我们不过是在享受着别人的成果跟着别人的思路云阅读源码了一遍。okhttp从早期的Java版本到Kotlin版本一直不断优化升级,实现细节上也作出了调整。重读源码加上自身的思考能深刻的理解okhttp的实现原理。 二、从基本使用说起 项目中引入依赖,Github地址okhttp dependencies 阅读详情

Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。

尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。
OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。

OkHttp 处理了很多网络疑难杂症:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。

使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果你用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。

注:在国内使用OkHttp会因为这个问题导致部分酷派手机用户无法联网,所以对于大众app来说,需要等待这个bug修复后再使用。或者尝试使用OkHttp的老版本。
截止到目前,OkHttp一直没有修复,并把修复计划延迟到了OkHttp2.3中。不是所有设备都能重现,仅少量设备会出现这个问题。(如果问题这么明显,OkHttp早就修复了)

入门

官方资料

官方介绍
github源码

使用范围

OkHttp支持Android 2.3及其以上版本。
对于Java, JDK1.7以上。

jar包准备

官方介绍页面有链接位置。这里把下载链接也写在下面。
OkHttp
Okio

基本使用

HTTP GET

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();    
    if (response.isSuccessful()) {        
        return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。

Response类:

public boolean isSuccessful()
Returns true if the code is in [200..300),
 which means the request was successfully received, understood, and accepted.

response.body()返回ResponseBody类
可以方便的获取string

public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset,
 this will attempt to decode the response body as UTF-8.Throws:
IOException

当然也能获取到流的形式:

public final InputStream byteStream()

HTTP POST
POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
 RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
  .url(url)
  .post(body)
  .build();
  Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
    return response.body().string();
} else {
    throw new IOException("Unexpected code " + response);
}
}

使用Request的post方法来提交请求体RequestBody

POST提交键值对
很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {

 RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();

  Request request = new Request.Builder()
  .url(url)
  .post(body)
  .build();

  Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
    return response.body().string();
} else {
    throw new IOException("Unexpected code " + response);
}
}

总结

通过上面的例子我们可以发现,OkHttp在很多时候使用都是很方便的,而且很多代码也有重复,因此特地整理了下面的工具类。
注意:

  • OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,可以使用clone方法,再进行自定义。这点在后面的高级教程里会提到。
  • enqueue为OkHttp提供的异步方法,入门教程中并没有提到,后面的高级教程里会有解释。

    import java.io.IOException;
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.message.BasicNameValuePair;
    import cn.wiz.sdk.constant.WizConstant;
    import com.squareup.okhttp.Callback;
    import com.squareup.okhttp.OkHttpClient;
    import com.squareup.okhttp.Request;
    import com.squareup.okhttp.Response; 
    
    public class OkHttpUtil {
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    static{
    mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    }
    /**
     * 该不会开启异步线程。
     * @param request
     * @return
     * @throws IOException
         */
        public static Response execute(Request request) throws IOException{
        return mOkHttpClient.newCall(request).execute();
        }
        /**
         * 开启异步线程访问网络
         * @param request
         * @param responseCallback
         */
    public static void enqueue(Request request, Callback responseCallback){
    mOkHttpClient.newCall(request).enqueue(responseCallback);
    }
    /**
     * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
     * @param request
     */
    public static void enqueue(Request request){
    mOkHttpClient.newCall(request).enqueue(new Callback() {
    
    @Override
    public void onResponse(Response arg0) throws IOException {
    
    }
    
    @Override
    public void onFailure(Request arg0, IOException arg1) {
    
    }
    });
    }
    public static String getStringFromServer(String url) throws IOException{
    Request request = new Request.Builder().url(url).build();
    Response response = execute(request);
    if (response.isSuccessful()) {
    String responseUrl = response.body().string();
    return responseUrl;
    } else {
    throw new IOException("Unexpected code " + response);
    }
    }
    private static final String CHARSET_NAME = "UTF-8";
    /**
     * 这里使用了HttpClinet的API。只是为了方便
     * @param params
     * @return
     */
    public static String formatParams(List<BasicNameValuePair> params){
    return URLEncodedUtils.format(params, CHARSET_NAME);
    }
    /**
     * 为HttpGet 的 url 方便的添加多个name value 参数。
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){
    return url + "?" + formatParams(params);
    }
    /**
     * 为HttpGet 的 url 方便的添加1个name value 参数。
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String attachHttpGetParam(String url, String name, String value){
    return url + "?" + name + "=" + value;
    }
    }  
    

高级

高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。

同步get

下载一个文件,打印他的响应头,以string形式打印响应体。
响应体的 string() 方法对于小文档来说十分方便、高效。但是如果响应体太大(超过1MB),应避免适应 string()方法 ,因为他会将把整个文档加载到内存中。
对于超过1MB的响应body,应使用流的方式来处理body。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
  System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

System.out.println(response.body().string());
}

异步get

在一个工作线程中下载文件,当响应可读时回调Callback接口。读取响应时会阻塞当前线程。OkHttp现阶段不提供异步api来接收响应体。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build();

client.newCall(request).enqueue(new Callback() {
  @Override public void onFailure(Request request, Throwable throwable) {
    throwable.printStackTrace();
  }

  @Override public void onResponse(Response response) throws IOException {
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }

    System.out.println(response.body().string());
  }
});
}

提取响应头

典型的HTTP头 像是一个 Map :每个字段都有一个或没有值。但是一些头允许多个值,像Guava的Multimap。例如:HTTP响应里面提供的Vary响应头,就是多值的。OkHttp的api试图让这些情况都适用。
当写请求头的时候,使用header(name, value)可以设置唯一的name、value。如果已经有值,旧的将被移除,然后添加新的。使用addHeader(name, value)可以添加多值(添加,不移除已有的)。
当读取响应头时,使用header(name)返回最后出现的name、value。通常情况这也是唯一的name、value。如果没有值,那么header(name)将返回null。如果想读取字段对应的所有值,使用headers(name)会返回一个list。
为了获取所有的Header,Headers类支持按index访问。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
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();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}

Post方式提交String

使用HTTP POST提交请求到服务。这个例子提交了一个markdown文档到web服务,以HTML方式渲染markdown。因为整个请求体都在内存中,因此避免使用此api提交大文档(大于1MB)。

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

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
String postBody = ""
    + "Releases\n"
    + "--------\n"
    + "\n"
    + " * _1.0_ May 6, 2013\n"
    + " * _1.1_ June 15, 2013\n"
    + " * _1.2_ August 11, 2013\n";

Request request = new Request.Builder()
    .url("https://api.github.com/markdown/raw")
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

Post方式提交流

以流的方式POST提交请求体。请求体的内容由流写入产生。这个例子是流直接写入Okio的BufferedSink。你的程序可能会使用OutputStream,你可以使用BufferedSink.outputStream()来获取。

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

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
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);
  }
};

Request request = new Request.Builder()
    .url("https://api.github.com/markdown/raw")
    .post(requestBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

Post方式提交文件

以文件作为请求体是十分简单的。

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

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
File file = new File("README.md");

Request request = new Request.Builder()
    .url("https://api.github.com/markdown/raw")
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

Post方式提交表单

使用FormEncodingBuilder来构建和HTML

标签相同效果的请求体。键值对将使用一种HTML兼容形式的URL编码来进行编码。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
    .add("search", "Jurassic Park")
    .build();
Request request = new Request.Builder()
    .url("https://en.wikipedia.org/w/index.php")
    .post(formBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

Post方式提交分块请求

MultipartBuilder可以构建复杂的请求体,与HTML文件上传形式兼容。多块请求体中每块请求都是一个请求体,可以定义自己的请求头。这些请求头可以用来描述这块请求,例如他的Content-Disposition。如果Content-Length和Content-Type可用的话,他们会被自动添加到请求头中。

private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
    .type(MultipartBuilder.FORM)
    .addPart(
        Headers.of("Content-Disposition", "form-data; name=\"title\""),
        RequestBody.create(null, "Square Logo"))
    .addPart(
        Headers.of("Content-Disposition", "form-data; name=\"image\""),
        RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
    .build();

Request request = new Request.Builder()
    .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
    .url("https://api.imgur.com/3/image")
    .post(requestBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

使用Gson来解析JSON响应

Gson是一个在JSON和Java对象之间转换非常方便的api。这里我们用Gson来解析Github API的JSON响应。

注意:ResponseBody.charStream()使用响应头Content-Type指定的字符集来解析响应体。默认是UTF-8。

private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("https://api.github.com/gists/c2a7c39532239ff261be")
    .build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
  System.out.println(entry.getKey());
  System.out.println(entry.getValue().content);
}
}

static class Gist {
Map<String, GistFile> files;
}

static class GistFile {
String content;
}

响应缓存

为了缓存响应,你需要一个你可以读写的缓存目录,和缓存大小的限制。这个缓存目录应该是私有的,不信任的程序应不能读取缓存内容。
一个缓存目录同时拥有多个缓存访问是错误的。大多数程序只需要调用一次new OkHttp(),在第一次调用时配置好缓存,然后其他地方只需要调用这个实例就可以了。否则两个缓存示例互相干扰,破坏响应缓存,而且有可能会导致程序崩溃。
响应缓存使用HTTP头作为配置。你可以在请求头中添加Cache-Control: max-stale=3600 ,OkHttp缓存会支持。你的服务通过响应头确定响应缓存多长时间,例如使用Cache-Control: max-age=9600。

private final OkHttpClient client;

public CacheResponse(File cacheDirectory) throws Exception {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);

client = new OkHttpClient();
client.setCache(cache);
}

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://publicobject.com/helloworld.txt")
    .build();

Response response1 = client.newCall(request).execute();
if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);

String response1Body = response1.body().string();
System.out.println("Response 1 response:          " + response1);
System.out.println("Response 1 cache response:    " + response1.cacheResponse());
System.out.println("Response 1 network response:  " + response1.networkResponse());

Response response2 = client.newCall(request).execute();
if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

String response2Body = response2.body().string();
System.out.println("Response 2 response:          " + response2);
System.out.println("Response 2 cache response:    " + response2.cacheResponse());
System.out.println("Response 2 network response:  " + response2.networkResponse());

System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
}

扩展

在这一节还提到了下面一句:
There are cache headers to force a cached response, force a network response, or force the network response to be validated with a conditional GET.

我不是很懂cache,平时用到的也不多,所以把Google在Android Developers一段相关的解析放到这里吧。

Force a Network Response
In some situations, such as after a user clicks a ‘refresh’ button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache directive:

connection.addRequestProperty("Cache-Control", "no-cache");

If it is only necessary to force a cached response to be validated by the server, use the more efficient max-age=0 instead:

connection.addRequestProperty("Cache-Control", "max-age=0");

Force a Cache Response
Sometimes you’ll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached directive:

try {
 connection.addRequestProperty("Cache-Control", "only-if-cached");
 InputStream cached = connection.getInputStream();
 // the resource was cached! show it
catch (FileNotFoundException e) {
 // the resource was not cached
 }
}

This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the max-stale directive with the maximum staleness in seconds:

int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks staleconnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);

以上信息来自:HttpResponseCache - Android SDK | Android Developers

取消一个Call

使用Call.cancel()可以立即停止掉一个正在执行的call。如果一个线程正在写请求或者读响应,将会引发IOException。当call没有必要的时候,使用这个api可以节约网络资源。例如当用户离开一个应用时。不管同步还是异步的call都可以取消。
你可以通过tags来同时取消多个请求。当你构建一请求时,使用RequestBuilder.tag(tag)来分配一个标签。之后你就可以用OkHttpClient.cancel(tag)来取消所有带有这个tag的call。

private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
    .build();

final long startNanos = System.nanoTime();
final Call call = client.newCall(request);

// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
  @Override public void run() {
    System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
    call.cancel();
    System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
  }
}, 1, TimeUnit.SECONDS);

try {
  System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
  Response response = call.execute();
  System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
      (System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
  System.out.printf("%.2f Call failed as expected: %s%n",
      (System.nanoTime() - startNanos) / 1e9f, e);
}
}

超时

没有响应时使用超时结束call。没有响应的原因可能是客户点链接问题、服务器可用性问题或者这之间的其他东西。OkHttp支持连接,读取和写入超时。

private final OkHttpClient client;

public ConfigureTimeouts() throws Exception {
client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
}

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
    .build();

Response response = client.newCall(request).execute();
System.out.println("Response completed: " + response);
}

每个call的配置

使用OkHttpClient,所有的HTTP Client配置包括代理设置、超时设置、缓存设置。当你需要为单个call改变配置的时候,clone 一个 OkHttpClient。这个api将会返回一个浅拷贝(shallow copy),你可以用来单独自定义。下面的例子中,我们让一个请求是500ms的超时、另一个是3000ms的超时。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
    .build();

try {
  Response response = client.clone() // Clone to make a customized OkHttp for this request.
      .setReadTimeout(500, TimeUnit.MILLISECONDS)
      .newCall(request)
      .execute();
  System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
  System.out.println("Response 1 failed: " + e);
}

try {
  Response response = client.clone() // Clone to make a customized OkHttp for this request.
      .setReadTimeout(3000, TimeUnit.MILLISECONDS)
      .newCall(request)
      .execute();
  System.out.println("Response 2 succeeded: " + response);
} catch (IOException e) {
  System.out.println("Response 2 failed: " + e);
}
}

处理验证

这部分和HTTP AUTH有关。

相关资料:HTTP AUTH 那些事 - 王绍全的博客 - 博客频道 - youkuaiyun.com

OkHttp会自动重试未验证的请求。当响应是401 Not Authorized时,Authenticator会被要求提供证书。Authenticator的实现中需要建立一个新的包含证书的请求。如果没有证书可用,返回null来跳过尝试。

public List<Challenge> challenges()
Returns the authorization challenges appropriate for this response's code. 
If the response code is 401 unauthorized, 
this returns the "WWW-Authenticate" challenges.
If the response code is 407 proxy unauthorized, this returns the "Proxy-Authenticate" challenges.
Otherwise this returns an empty list of challenges.

当需要实现一个Basic challenge, 使用Credentials.basic(username, password)来编码请求头。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
client.setAuthenticator(new Authenticator() {
  @Override public Request authenticate(Proxy proxy, Response response) {
    System.out.println("Authenticating for response: " + response);
    System.out.println("Challenges: " + response.challenges());
    String credential = Credentials.basic("jesse", "password1");
    return response.request().newBuilder()
        .header("Authorization", credential)
        .build();
  }

  @Override public Request authenticateProxy(Proxy proxy, Response response) {
    return null; // Null indicates no attempt to authenticate.
  }
});

Request request = new Request.Builder()
    .url("http://publicobject.com/secrets/hellosecret.txt")
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

转自 OkHttp使用介绍 同时整合了 OkHttp使用进阶 这篇文章以及其中的评论。

OkHttp官方教程解析-彻底入门OkHttp使用 最近半年来身边开发的朋友越来越多的提到OkHttp,上谷歌百度一下,确实OkHttp成了时下最火的HTTP框架,于是我也开始放下Volley,转而关注OkHttp,五一期间仔细看了官方WiKi介绍(我喜欢学习官方的文档),现在把自己整理的官方教程分享给大家,希望给初学者带来帮助。        OkHttp官网地址:http://square.github.io/okhttp/ 阅读详情

相关推荐

基本使用——OkHttp3详细使用教程

概述 OkHttp现在应该算是最火的Http第三方库,Retrofit底层也是使用OkHttp,网上很多教程都写的不错,但是有些我认为重要的知识,大多一笔带过,所以我决定写一篇入门文章 OkHttp官网地址:http://square.github.io/okhttp/ OkHttp GitHub地址:https://github.com/square/okhttp 出现背景 网络...

薛瑄的博客 6万+

okhttp

Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。 关于HttpURLConnection和HttpClient的选择>>官方博客 尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。 OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以

鑫的专栏 822

Android进阶之路 - OkHttp的入门使用

因前一篇并没有把具体的效果图展现,故本篇讲解的同样是okHttp下的Get请求与Post请求,不包含文件与图片的上传与下载(之后可能在中级使用中讲到)前提 (使用了三方平台的接口) :Effect :还有一些主要注意,可通过上一篇okHttp查看,链接地址如下:http://blog.youkuaiyun.com/qq_20451879/article/details/55001505MainActivity

Android、前端、小程序、后端 2386

OkHttp3详细使用教程

OkHttp官网地址:http://square.github.io/okhttp/ OkHttp GitHub地址:https://github.com/square/okhttp implementation(&amp;amp;amp;amp;amp;quot;com.squareup.okhttp3:okhttp:3.12.0&amp;amp;amp;amp;amp;quot;) get同步请求 /** * 放在子线程中执行 */

qq_36699930的博客 7790

OkHttp3入门-手把手教你如何用

OkHttp3入门准备工作添加依赖设置网络权限创建简单创建四步走异步请求同步请求中止请求具体介绍GET请求POST请求下载(保存到本地)简单的下载请求(示例)准备工作显示下载进度上传文件上传文件上传(简单示例)涉及到的类与方法上传监听(显示上传进度)其他拦截器可能涉及到的类与方法 OkHttp是一个处理网络请求的开源项目; 安卓端轻量级框架; 用于替代HttpUrlConnection和Apache HttpClient; 准备工作 添加依赖 //网络请求OkHttp3 implementation 'com.squareup.okhttp3:okhttp:4.3.1' 设置网络权限 A

AT32F421玩转AM32电调:手把手教你调试过零点比较器,告别电机抖动

本文详细介绍了如何使用AT32F421芯片调试AM32电调的过零点比较器,解决电机抖动问题。通过硬件配置、软件环境搭建、比较器电路原理分析及filter_level参数动态调整等实战步骤,帮助开发者精准诊断和优化电机控制性能。

weixin_42525632的博客 278

OkHttp Digest 项目使用教程

OkHttp Digest 项目使用教程 1. 项目的目录结构及介绍 OkHttp Digest 项目的目录结构如下: okhttp-digest/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ ├── io/ │ │ │ │ ├── github/ │ │ │ │ │ ├── rburgst/ │ ...

gitblog_00780的博客 533

如何免费访问和使用Gemini API?

Gemini Ultra具有最先进的性能,在几个指标上超过了GPT-4的性能。它是第一个在大规模多任务语言理解基准测试中超越人类专家的模型,该基准测试57个不同学科的世界知识和解决问题的能力。Gemini是谷歌迄今为止开发的最先进、最庞大的AI模型。它为多模态而建,理解并处理不同类型的数据,比如文本、代码、音频、图像和视频。下面我们将加载Masood Aslami的图像,并用它来测试Gemini Pro Vision的多模态性。有了Gemini可以为查询提供图像、音频和文本,获得几乎完美的答案。

java_cjkl的博客 1万+

OkHttp-Signpost 使用教程

OkHttp-Signpost 使用教程 项目介绍 OkHttp-Signpost 是一个用于签名 OkHttp 请求的 Signpost 扩展。它允许开发者轻松地将 OAuth 签名应用于 OkHttp 请求,从而实现安全的 API 调用。该项目由 Patrik Åkerfeldt 开发,遵循 Apache License 2.0 许可。 项目快速启动 安装依赖 首先,在项目的 build.gr...

gitblog_00090的博客 685

PHP项目实战:易宝支付SDK对接全流程(含回调处理与常见问题排查)

本文详细介绍了PHP项目中易宝支付SDK的对接全流程,包括环境准备、SDK配置、支付请求构建与发起、回调处理实战以及常见问题排查。特别针对回调处理环节的常见问题提供了解决方案,帮助开发者快速完成支付对接并优化性能。

weixin_29007809的博客 389

使用Python进行核磁数据预处理

随着医学与人工智能技术的快速崛起,伴随算法算力、数据等关键要素的积累和突破,人工智能技术在精准医学领域的科研应用也随之飞快增长,相关科研成果和学术论文数量逐年激增,医学影像人工智能涉及的技术如图像分割、病灶识别、病灶自动勾画、影像组学、深度学习模型构建和临床信息解析越来越趋于分析流程化,模块化,帮助越来越多的医生在临床科研实践中获得突破性的进展。根据具体的应用和数据类型,你可能需要调整或添加额外的步骤。对于更高级的处理,如图像分割或NMR数据的复杂处理,你可能需要查阅更专业的文献或使用更专业的软件工具。

xhlo521的博客 3133

OkHttp 使用教程

OkHttp 使用教程 项目介绍 OkHttp 是一个高效的 HTTP 客户端,广泛应用于 Java 和 Android 应用程序中。它由 Square 公司开发,旨在提供更快的资源加载速度和节省带宽。OkHttp 支持 HTTP/2、连接池、GZIP 压缩、响应缓存等特性,能够从常见的连接问题中无声恢复,并支持现代 TLS 功能。 项目快速启动 安装 OkHttp 首先,在项目的 build.g...

gitblog_00768的博客 503

零基础手把手教你做FMEDA

本文通过分步骤手把手来教大家具体如何做FMEDA,希望对工作中要做FMEDA的童鞋有帮助。对于工作当中用不到FMEDA的童鞋,也可以作为科普知识,更好地了解一下FMEDA及硬件功能安全。

NewCarRen的博客 9935

【亲测免费】 OkHttp Digest 使用教程

OkHttp Digest 使用教程 项目介绍 okhttp-digest 是一个为 OkHttp 客户端库设计的摘要式认证组件。它源自 Apache Http Client 的经典实现,并迁移到了 Maven Central。该项目的主要目的是提供一个安全、高效的认证机制,适用于需要 HTTP 摘要认证的场景。 项目快速启动 添加依赖 首先,在你的 pom.xml 文件中添加 okhttp-di...

gitblog_00032的博客 1133

RK3568(buildroot)利用squashfs+overlay实现嵌入式系统高可靠存储方案

本文详细介绍了在RK3568嵌入式平台上,基于Buildroot系统,利用squashfs只读根文件系统与overlayfs可写层相结合的高可靠存储方案。该方案能有效防止设备意外断电导致的系统文件损坏,通过内核配置、启动脚本编写及镜像制作,实现系统核心的只读保护与用户数据的持久化分离,显著提升嵌入式设备的现场稳定性。

weixin_29189381的博客 548

直击高频编程考点:字符串知识及经典算法题总结

字符串相关基本练习题总结(最长公共子串、最长回文子串、最长无重复字符子串、最小覆盖子串、字符串相乘、中文数字表达转实际数字格式等)

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 172万+

OkHttp Idling Resource 使用教程

OkHttp Idling Resource 使用教程 1. 项目的目录结构及介绍 OkHttp Idling Resource 项目的目录结构如下: okhttp-idling-resource/ ├── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── jakewharton/ │ │...

gitblog_00417的博客 502

手把手教你学Simulink——基于Simulink的无迹卡尔曼滤波(UKF)控制仿真建模示例

本文详细介绍了在Simulink中实现无迹卡尔曼滤波(UKF)控制倒立单摆系统的完整过程。通过对比扩展卡尔曼滤波(EKF),重点阐述了UKF在处理强非线性系统时的优势:采用无迹变换(UT)通过确定性采样捕捉非线性特性,精度可达三阶泰勒展开且无需计算雅可比矩阵。文章分步骤讲解了状态空间定义、UKF参数设计、Simulink实现方法,以及结合LQR控制器的闭环系统搭建,并通过仿真验证UKF在大角度偏移情况下具有更优的估计精度和控制性能。最后还讨论了工程实践要点和扩展方向,为非线性系统控制提供了实用解决方案。

MHD0815的博客 97

Android Studio OKhttp 使用教程 登录界面

Android Studio OKhttp 使用教程 对于学习Android Studio 的同学来说,不要单单只局限于学习组件的使用方法,我们应该用实用程序来体验一下Android 开发的使用效果,增加一些兴趣。那我们来先做一个简单的登录界面。 我们先来看一下具体效果。 接下来就让我们一起来做一下如何实现简单的登录。 导入依赖 implementation('com.squareup.ok...

孑桀 2831

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

OKhttp使用教程,okhttp post 提交JSON数据

文章目录 前言 一、pandas是什么? 二、使用步骤 1.引入库 2.读入数据 总结 前言 昨天开始接手一个小任务,说让我处理一个接口的查询返回数据,最开始的时候,我发现自己很傻逼,还想着自己写一个关于提交的方式,就是自己把拿到的数据封装到head,body当中,做了一早上,我发现好像有点难,不知道怎么处理该问题,但是在最后的时候。我师父过来一看,来一句,okhttp啊 ,你在搞啥子哦。一瞬间,我发现自己好像没有在开发的这条路上,这么好的工具怎么不用呢。对不。下面我就...

阿杜的博客 1万+

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

上一篇: Fiddler简介
下一篇: Retrofit使用教程
System_err
博客等级 码龄10年 52粉丝 122原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值