Java EE Architecture Design--design of network framework based on OKHTTP3

Source: Internet
Author: User
Tags ascii hex values

Reprint Please specify source: http://blog.csdn.net/smartbetter/article/details/77893903

This article takes you to design a set of satisfying business requirements, code robust and efficient (cohesion-poly low-coupling) and extensible network Framework. Based on the latest OKHTTP3, we design an efficient and reliable network cache, multi-threaded file download and other architecture modules. This is not limited to the use of other people's framework, and entered the design framework, so that they can go farther, I think this is a qualified developer should have the ability. In development, there are many criteria for choosing an open source framework, such as the cost of learning, whether the documentation is complete, the number of GitHub stars, whether someone is currently maintaining it, how popular it is, whether the code is designed for reference, or code size.

First look at the current mainstream network framework comparison:

Network Framework Description Open Source Address
Okhttp HTTP+HTTP/2 Client for Android and Java applications Https://github.com/square/okhttp
Retrofit The corresponding encapsulation is done on the okhttp, decoupling, annotation processing, simplifying the code, support uploading and downloading files, support auto-change parsing mode, support various HTTP request libraries Https://github.com/square/retrofit

HTTP Network framework Design diagram:

Many open source frameworks are now network requests that use Okhttp to do the underlying protocol. So we apply the trend of the times, use Okhttp to do network requests, instead of using traditional httpurlconnection.

1.http protocol

HTTP protocol, Hypertext Transfer Protocol, the most common or http1.1 version of the current use, but we also come to understand the following http2.0 protocol:

Features of http1.1:

1)支持客户/服务器模式2)简单快速,GET、POST(http的几种请求方式:Get、POST、HEAD、PUT、DELETE、TRACE、CONNECT、OPTIONS。)3)灵活,允许传输任意类型的数据对象。4)无连接,限制每次连接只处理一个请求。5)无状态,协议对于事务处理没有记忆能力。

http2.0 contrast http1.1 added features:

1)多路复用允许同时通过单一的HTTP/2连接发起多重的请求-响应消息,单连接多资源的方式减少服务端的链接压力,内存占用更少,连接吞吐量更大,由于TCP连接的减少而使网络拥塞状况得以改善,同时TCP慢启动时间的减少,使拥塞和丢包恢复速度更快;2)头部压缩,每次都要传输UserAgent、Cookie这类不会变动的内容,使用HPACK算法进行压缩;3)对请求划分优先级;4)服务器推送流(即Server Push技术)。

Some response codes returned by the HTTP request:

100-101:信息提示; 200-206:成功; 300-305:重定向; 400-415:客户端错误; 500-505:服务器错误。
2. Cornerstone of the network framework OKHTTP3

Need to add Maven dependencies:

<!--okhttp3--><dependency> <groupid>com.squareup.okhttp3</groupid> <artifactid>okhttp </artifactid> < version>3.9.0</version></DEPENDENCY>        

Instructions on how to use the okhttp in the official documentation: http://square.github.io/okhttp/, we'll add a note to Okhttp below.

Synchronous requests and asynchronous requests for 1.okhttp

Synchronous requests (using JUnit to write test methods):

new OkHttpClient();Request request = new Request.Builder().url(url).build();try {    Response response = client.newCall(request).execute();    if (response.isSuccessful()) {        System.out.println(response.body().string());    }} catch (IOException e) { e.printStackTrace();}

Asynchronous Request:

system.out.println ( Thread.CurrentThread (). GetId ()) okhttpclient client = new okhttpclient (); Request Request = new request.builder (). URL (URL). build (); Client.newcall (Request). Enqueue (new Callback () { @Override public void onfailure (call call, IOException e) {}  @Override public void onresponse (call call, Response Response) throws IOException { Span class= "Hljs-keyword" >if (response.issuccessful ()) {System.out.println (Thread.CurrentThread (). GetId ());}}); 

Practical application of 2.okhttp request head and response head

Request header can be consulted: Http://tools.jb51.net/table/http_header

Okhttpclient client =New Okhttpclient (); Request Request =New Request.builder (). URL ("Http://www.baidu.com"). AddHeader ( "User-agent", " applewebkit/537.36 (khtml, like Gecko) chrome/46.0.2490.71 SAFARI/5 37.36 "). AddHeader ( "accept-encoding",  "identity"). Build (); try {Response Response = Client.newcall (Request). Execute (); if (response.issuccessful ()) {Headers Headers = Response.headers (); for (int i = 0; i < headers.size (); i++) { System.out.println (Headers.name (i) +  ":" + headers.value (i));}}} catch (IOException e) {e.printstacktrace ();        
3.okhttp get requests and post requests

Get is used for information acquisition, and should be secure and idempotent.

Request features
Get Get is used for information acquisition, and should be secure and idempotent, so-called security means that the operation is used to obtain information rather than modify information, without affecting the state of the resource. Idempotent means that multiple requests to the same URL should return the same result.
Post Post is used to modify resources on the server, it is important to note that post must be to form (form).

GET Request:

new OkHttpClient();HttpUrl httpUrl = HttpUrl.parse("http://localhost:8080/web/HelloServlet")        .newBuilder()        .addQueryParameter("username", "user")        .addQueryParameter("password", "user123") .build();Request request = new Request.Builder().url(httpUrl.toString()).build();try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { System.out.println(response.body().string()); }} catch (IOException e) { e.printStackTrace();}

POST request:

By default, the form data is encoded as "application/x-www-form-urlencoded". That is, all characters are encoded before being sent to the server, the spaces are converted to "+", and the special symbols are converted to ASCII hex values.

In addition to this, there is a multipart/form-data, which does not encode characters, which must be used when using a form that contains a control uploaded by a file, such as a photo upload, and so on. The okhttp has been packaged for multipart/form-data, simplifying many operations.

okhttpclient client = new okhttpclient (); Formbody BODY = new formbody.builder (). Add ( "username",  "user") //if it contains Chinese you need to call the Addencoded method to transcode instead of the Add method. Add (new request.builder (). URL ( "http://localhost : 8080/web/helloservlet "). Post (body). Build (); try {Response Response = Client.newcall (Request). Execute (); if (response.issuccessful ()) {System.out.println (Response.body (). String ());}} catch (IOException e) {e.printstacktrace ();        
3.okhttp upload file 1.mutipart protocol upload file

The ability to upload files yourself is relatively complex. First, you need to understand the meaning of the specific protocol in the HTTP request process after the file is uploaded, because you need to encapsulate some of the parameter information in the middle, and second, you need to build a Web service yourself.

The backend interface can use FileUpload to implement the File Upload section in reference to http://blog.csdn.net/smartbetter/article/details/52056377.

2.okhttp uploading files using the Mutipart protocol
Requestbody imagebody = requestbody.create (Mediatype.parse ("Image/jpeg"),New File ( "/users/macos/desktop/temp.jpg"); Multipartbody BODY = new multipartbody.builder (). SetType (multipartbody.form). Ad Dformdatapart ( "name",  "Zhangsan"). Addformdatapart ( "filename",  "temp.jpg", Imagebody). Build (); Okhttpclient client = Span class= "Hljs-keyword" >new okhttpclient (); Request Request = new request.builder (). URL (try {Response Response = Client.newcall (Request). Execute (); if (response.issuccessful ()) {System.out.println (Response.body (). String ());}} catch (IOException e) {e.printstacktrace ();        
The principle and key fields of caching in the 4.okhttp data cache 1.http Protocol

Cache key Fields:

Expires:指示响应内容过期的时间,格林威治时间GMTCatche-Control:    | no-cache:无缓存指令    | max-age:如果缓存只是用来和服务器做验    | only-if-cached:有时你会想显示可以立即    | max-stale:设置最长过期时间来允许过期的response响应(有时候过期的response比没有response更好)。Last-Modified:判断客户端数据和服务端数据有没有变化。如果相同表示没有人修改,如果修改则Last-Modified事件发生变化。ETag:对服务器返回的整个response做了相应的编码处理,得到了一个加密的值。Date:If-Modified-Since:请求头中标识的,客户端存取的该资源最后一次修改的时间,同Last-Modified。If-None-Match:请求头中标识的。
2.okhttp implementation of data caching

Okhttp Cache Related classes: Cacheinterceptor, Cachestrategy, Cache, Disklrucache.

int maxcachesize =10 *1024 *1024; Cache cache =New Cache (New File ("/users/macos/desktop/source"), maxcachesize); Okhttpclient client =New Okhttpclient.builder (). cache (Cache). build (); Request Request =new request.builder (). URL ( "http://www.163.com/"). CacheControl (new cachecontrol.builder (). Maxstale (365, timeunit.days). Build ()). build (); Response Response = client.newcall (Request). Execute (); String body1 = Response.body (). String (); System.out.println ( "network Response" + response.networkresponse ()); System.out.println ( "cache response" + response.cacheresponse ()); System.out.println ( "**************************"); Response response1 = client.newcall (Request). Execute (); String body2 = Response1.body (). String (); System.out.println ( "network Response" + response1.networkresponse ()); System.out.println ( "cache response" + response1.cacheresponse ());     

We run this test class, as shown below, and we can see that the network was requested, and then the cache was requested:

Java EE Architecture Design--design of network framework based on OKHTTP3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.