完全開源Android網絡框架 — 基於JAVA原生的HTTP框架


HttpNet網絡請求框架基於HttpUrlConnection,采用Client + Request + Call的請求模型,支持https默認證書,數字安全證書、支持http代理!后續將會實現隊列、緩存模塊。

開源地址:Github上HttpNet,碼雲上:HttpNet

項目結構如下:

HttpNet項目結構

使用方法:

compile 'com.haibin:httpnet:1.0.5'

 

HttpNetClient client = new HttpNetClient();//構建一個客戶端

client.setProxy("192.168.1.1",80);//您也可以開啟該客戶端全局代理

默認支持Https認證,如果使用數字證書,在執行請求之前使用下面3種API導入證書即可

client.setSslSocketFactory(getAssets().open("12306.cer"));//證書文件輸入流
client.setSslSocketFactory("filepath/12306.cer");//證書路徑
client.setSslSocketFactoryAsString("cerValue");//證書文本

//注意,添加多個證書只能調用該方法一次,可以使用如下方式添加多個證書,該客戶端導入證書之后將不能訪問其它沒有導入https的鏈接,可以重新創建一個HttpNetClient即可

InputStream is12306 = getAssets().open("12306.cer");
InputStream isGoogle = getAssets().open("google.cer");
client.setSslSocketFactory(is12306 , isGoogle );

Request request = new Request.Builder()
                .encode("UTF-8")
                .method("GET")
                .timeout(13000)
                .proxy("192.168.1.1",80) //支持HTTP代理
                .url("https://kyfw.12306.cn/otn/")
                .build();

 

GET請求構建:

Request request = new Request.Builder().encode("UTF-8")
                .method("GET")
                .timeout(13000)
                .url("http://www.oschina.net")
                .build();

 

POST請求構建:

RequestParams params = new RequestParams()
                .put("userName","oscer")
                .putFile("fileName","file")
                .put("pwd","oschina");
        Request request = new Request.Builder()
                .encode("UTF-8")
                .method("POST")
                .params(params)
                .timeout(13000)
                .url("http://www.oschina.net")
                .build();

 

POST JSON請求構建:

Request request = new Request.Builder()
                .encode("UTF-8")
                .method("POST")
                .content(new JsonContent("json")
                .timeout(13000)
                .url("http://www.oschina.net")
                .build();

 

執行請求:

client.newCall(request).execute(new CallBack() {
            @Override
            public void onResponse(Response response) {
                String body = response.getBody();
                InputStream is = response.toStream();//如果采用下載
            }

            @Override
            public void onFailure(Exception e) {

            }
        });

此項目無任何內存泄露,高效優雅!

開源地址:Github上HttpNet,碼雲上:HttpNet


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM