HttpNet網絡請求框架基於HttpUrlConnection,採用Client + Request + Call的請求模型,支持https默認證書,數字安全證書、支持http代理!後續將會實現隊列、緩存模塊。git
開源地址:Github上HttpNet,碼雲上:HttpNetgithub
項目結構以下:json
使用方法:緩存
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();
執行請求:ide
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) { } });
此項目無任何內存泄露,高效優雅!ui