HttpUtils的使用
1.從github上匯入框架 https://github.com/hongyangAndroid/okhttputils 專案使用的是 compile 'com.zhy:okhttputils:2.6.2'
2.在MyApplication的Oncreate()方法中進行初始化
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
.cookieJar(new CookieJarImpl(new MemoryCookieStore()))//記憶體儲存cookie
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
.hostnameVerifier(new HostnameVerifier() {//允許訪問https網站,並忽略證書
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpUtils.initClient(okHttpClientBuilder.build());
3.做了一個二次封裝,方便呼叫
/**
* post json請求
*
* @param obj 實體類物件
* @param stringCallback 對資料的處理,在ui執行緒執行
*/
public static void doPostByJson(Object obj, StringCallback stringCallback) {
if (obj == null || stringCallback == null) {
return;
}
OkHttpUtils
.postString()
.url(NewConstants.URL)
.content(new Gson().toJson(obj))
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.build()
.execute(stringCallback);
}
4.在程式碼中直接呼叫doPostByJson方法即可,資料在onResponse中得到,同時可在此方法直接更新UI,是不是很方便??
private void loadByPostJson() {
Httputils.doPostByJson(initParams(), new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
tip(response);
tip("success");
}
});
}
相關文章
- 在Java中,使用HttpUtils實現傳送HTTP請求JavaHTTP
- Scrapy框架的使用之Scrapyrt的使用框架
- Docker框架的使用系列教程(四)容器的使用Docker框架
- Docker的使用Docker
- pip 的使用
- Redis的使用Redis
- MongoDB的使用MongoDB
- mysql的使用MySql
- Typeof的使用
- iview 的使用View
- git的使用Git
- IntentService的使用Intent
- RestTemplate的使用REST
- lombok的使用Lombok
- MybatisGenerator的使用MyBatis
- elasticsearch的使用Elasticsearch
- SVG 的使用SVG
- sqlmap的使用SQL
- Promise的使用Promise
- git 的使用Git
- postman的使用Postman
- git的使用+Git
- joomla的使用OOM
- Nginx的使用Nginx
- SwitchHosts的使用
- pipenv 的使用
- BitArray的使用
- PHPeof的使用PHP
- kendoTooltip的使用
- ionicsqlite的使用SQLite
- webview的使用WebView
- RecyclerView的使用View
- WKWebView 的使用WebView
- Qunit的使用
- ubuntu的使用Ubuntu
- JDBC的使用JDBC
- CardView的使用View
- sqlldr的使用SQL