OKHttpClient使用示例

OKHttpClient是一个类似HttpClient的工具,用于模拟Http,https的请求。语法使用方面要比HttpClient更简洁。

1、Jar包下载

maven引入:

    <dependency>
      <groupId>com.squareup.okhttp</groupId>
      <artifactId>okhttp</artifactId>
      <version>2.2.0</version>
      <scope>compile</scope>
    </dependency>

手动下载:

下载以下jar文件导入工程即可:

okhttp-2.2.0.jar

okio-1.2.0.jar

2、示例代码

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
	.url("http://www.baidu.com")
	.header("User-Agent", "OkHttp Headers.java")
	.build();

Response response = client.newCall(request).execute();

System.out.println("Result: " + response.isSuccessful());
System.out.println("Server: " + response.header("Server"));
System.out.println("ResponseBody: " + response.body().string());

3、其他功能

  1. 使用 GZIP 压缩减少传输的数据量;
  2. 缓存,减少重复请求;
  3. SPDY;
  4. 连接池;
  5. 失败重试(如果你的服务有多个 IP 地址,如果第一次连接失败,OkHttp 将使备用地址);

猜你喜欢

转载自blog.csdn.net/testguess/article/details/52734840
今日推荐