1. 程式人生 > >okhttp,讓你的網路請求變得更加簡單。

okhttp,讓你的網路請求變得更加簡單。

我們後端在工作中,可能接觸最多的無非是介面請求了,之前用的最多的是httpclient,後來通過一系列的對比可以發現,okhttp比httpclient更加優秀。因此,寫了OkHttp-FastJson,一個讓網路請求更簡單的框架。

OkHttp-FastJson是什麼?

  • 網路框架使用最熱門的OkHttp3,比HttpClient效能更強,引用api更簡單!
  • 自動幫你解析請求響應的JSON資料,讓你專注於處理業務邏輯。JSON解析用阿里的fastJson,速度比gson和fackson更快,引用api更簡單!

快速入門

  • 克隆本專案,並mvn install。
  • 在pom.xml引入okhttp-fastjson。
    <dependency>
        <groupId>github.hjg</groupId>
    <artifactId>okhttp-fastjson</artifactId>
    <version>1.0.0</version>
</dependency>
  • okhttp-fastjson提供了三種請求方式
     /**
     * 自定義請求
     * 
     * @param request
     * @param responseType
     * @param
<T> * @return * @throws InterfaceException */
public <T> T requestForObject(Request request, Class<T> responseType) throws InterfaceException { ObjectExtractor<T> extractor = new ObjectExtractor<>(fastJsonHelper(), responseType); return
handleResponse(null, request, extractor); }
    /**
     * GET
     * 
     * @param url
     * @param responseType
     * @param uriVariables
     * @param <T>
     * @return
     * @throws InterfaceException
     */
    public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws InterfaceException {
        Request request = new Request.Builder().url(StringUriTemplateUtil.expand(url, uriVariables)).build();
        ObjectExtractor<T> extractor = new ObjectExtractor<>(fastJsonHelper(), responseType);
        return handleResponse(null, request, extractor);
    }
     /**
     * POST
     * @param url
     * @param responseType
     * @param content
     * @param mediaType
     * @param <T>
     * @return
     * @throws InterfaceException
     */
    public <T> T postForObject(String url, Class<T> responseType, String content, MediaType mediaType)
            throws InterfaceException {
        Request request = new Request.Builder().url(url).post(RequestBody.create(mediaType, content)).build();
        ObjectExtractor<T> extractor = new ObjectExtractor<>(fastJsonHelper(), responseType);
        return handleResponse(null, request, extractor);
    }
  • 這是get請求的例子。
  • 新建web專案,新建JavaBean:ProductVo類和測試類TestController類,然後“../test/getService”模擬Web介面服務端,“../test/get”模擬客戶端去呼叫服務端

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;


public class ProductVo {
    private int id ;
    private String name ;
    private double price ;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.JSON_STYLE);
        return ReflectionToStringBuilder.toString(this);
    }
}
import github.hjg.InterfaceException;
import github.hjg.JsonInterface;
import github.hjg.OkHttpInterface;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
        //模擬服務端
        @GetMapping("/getService")
        public String  getService() {
                return "{\"id\":1,\"name\":\"test\",\"price\":23.01}";
        }
        //模擬客戶端
    @GetMapping("/get")
    public String getTest() throws InterfaceException {
       OkHttpInterface okhttpInterface = new JsonInterface();
       ProductVo product = okhttpInterface.getForObject("http://localhost:8080/test/getService", ProductVo.class,"");
       return product.toString();
    }
 {
id: 1,
name: "test",
price: 23.01
}
  • 當然你也能根據具體需求去自定義OkHttpInterface的引數配置
    OkHttpInterface okHttpInterface = new JsonInterface(
        new OkHttpConfig.Builder()
            .connectTimeout(3000) //配置連線超時引數,預設10000
            .readTimeout(3000) //讀超時引數,預設10000
            .writeTimeout(3000) //寫超時引數,預設10000
            //以及對這些連線的的連線新池引數配置
            .maxIdleConnections(5) //最大空閒連線數,預設5個
            .keepAliveDuration(300000).build()); //,最大存活時間,預設300000