博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
An HTTP & HTTP/2 client for Android and Java applications OkHttp
阅读量:6123 次
发布时间:2019-06-21

本文共 3333 字,大约阅读时间需要 11 分钟。

 

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that’s efficient by default:

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.

http://square.github.io/okhttp/

GET A URL

This program downloads a URL and print its contents as a string. 

package okhttp3.guide;import java.io.IOException;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class GetExample {  OkHttpClient client = new OkHttpClient();  String run(String url) throws IOException {    Request request = new Request.Builder()        .url(url)        .build();    try (Response response = client.newCall(request).execute()) {      return response.body().string();    }  }  public static void main(String[] args) throws IOException {    GetExample example = new GetExample();    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");    System.out.println(response);  }}

 

POST TO A SERVER

This program posts data to a service. 

package okhttp3.guide;import java.io.IOException;import okhttp3.MediaType;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class PostExample {  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();    try (Response response = client.newCall(request).execute()) {      return response.body().string();    }  }  String bowlingJson(String player1, String player2) {    return "{'winCondition':'HIGH_SCORE',"        + "'name':'Bowling',"        + "'round':4,"        + "'lastSaved':1367702411696,"        + "'dateStarted':1367702378785,"        + "'players':["        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"        + "]}";  }  public static void main(String[] args) throws IOException {    PostExample example = new PostExample();    String json = example.bowlingJson("Jesse", "Jake");    String response = example.post("http://www.roundsapp.com/post", json);    System.out.println(response);  }}

 

 

转载地址:http://rifua.baihongyu.com/

你可能感兴趣的文章
centos 下安装g++
查看>>
嵌入式,代码调试----GDB扫盲
查看>>
类斐波那契数列的奇妙性质
查看>>
配置设置[Django]引入模版之后报错Requested setting TEMPLATE_DEBUG, but settings are not configured....
查看>>
下一步工作分配
查看>>
Response. AppendHeader使用大全及文件下载.net函数使用注意点(转载)
查看>>
Wait Functions
查看>>
代码描述10313 - Pay the Price
查看>>
jQuery最佳实践
查看>>
centos64i386下apache 403没有权限访问。
查看>>
vb sendmessage 详解1
查看>>
jquery用法大全
查看>>
Groonga 3.0.8 发布,全文搜索引擎
查看>>
PC-BSD 9.2 发布,基于 FreeBSD 9.2
查看>>
网卡驱动程序之框架(一)
查看>>
css斜线
查看>>
Windows phone 8 学习笔记(3) 通信
查看>>
重新想象 Windows 8 Store Apps (18) - 绘图: Shape, Path, Stroke, Brush
查看>>
Revit API找到风管穿过的墙(当前文档和链接文档)
查看>>
Scroll Depth – 衡量页面滚动的 Google 分析插件
查看>>