網(wǎng)絡(luò)請(qǐng)求的封裝
package com.lt.okhttpfirst.helper;
import android.content.Context;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
* Created by 風(fēng)情萬(wàn)種冷哥哥 on 2016/10/17.
*/
public class OkHttpClientHelper {
private static OkHttpClient mOkHttpClient = null;
private static OkHttpClientHelper mOkHttpUtils = null;
private OkHttpClientHelper(Context context) {
mOkHttpClient = getOkHttpSingletonInstance();
//開啟響應(yīng)緩存
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
//設(shè)置緩存目錄和大小
int cacheSize = 10 << 20; // 10 MiB
Cache cache = new Cache(context.getCacheDir(), cacheSize);
mOkHttpClient.setCache(cache);
//設(shè)置合理的超時(shí)
mOkHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
mOkHttpClient.setReadTimeout(20, TimeUnit.SECONDS);
mOkHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
//以下驗(yàn)證不設(shè)置素征,那么默認(rèn)就已經(jīng)設(shè)置了驗(yàn)證
mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
public static OkHttpClientHelper getOkHttpClientUtils(Context context) {
if (mOkHttpUtils == null) {
synchronized (OkHttpClientHelper.class) {
if (mOkHttpUtils == null) {
mOkHttpUtils = new OkHttpClientHelper(context);
}
}
}
return mOkHttpUtils;
}
public static OkHttpClient getOkHttpSingletonInstance() {
if (mOkHttpClient == null) {
synchronized (OkHttpClient.class) {
mOkHttpClient = new OkHttpClient();
}
}
return mOkHttpClient;
}
///////////////////////////////////////////////////////////////////////////
// GET方式網(wǎng)絡(luò)訪問(wèn)
///////////////////////////////////////////////////////////////////////////
/**
* 基方法集嵌,返回Request對(duì)象
*
* @param urlString
* @param tag
* @return
*/
private Request buildGetRequest(String urlString, Object tag) {
Request.Builder builder = new Request.Builder();
builder.url(urlString);
if (tag != null) {
builder.tag(tag);
}
return builder.build();
}
/**
* 自定義方法,返回Response對(duì)象
*
* @param urlString
* @return
* @throws IOException
*/
private Response buildResponse(String urlString, Object tag) throws IOException {
Request request = buildGetRequest(urlString, tag);
Response response = mOkHttpClient.newCall(request).execute();
return response;
}
//基礎(chǔ)方法御毅,返回ResponseBody對(duì)象
private ResponseBody buildResponseBody(String urlString, Object tag) throws IOException {
Response response = buildResponse(urlString, tag);
if (response.isSuccessful()) {
return response.body();
}
return null;
}
/**
* 作用:實(shí)現(xiàn)網(wǎng)絡(luò)訪問(wèn)文件根欧,將獲取到數(shù)據(jù)儲(chǔ)存在文件流中
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @return InputStream
*/
public static InputStream getStreamFromURL(Context context, String urlString, Object tag)
throws IOException {
ResponseBody body = getOkHttpClientUtils(context).buildResponseBody(urlString, tag);
if (body != null) {
return body.byteStream();
}
return null;
}
/**
* 作用:實(shí)現(xiàn)網(wǎng)絡(luò)訪問(wèn)文件,將獲取到的數(shù)據(jù)存在字節(jié)數(shù)組中
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @return byte[]
*/
public static byte[] getBytesFromURL(Context context, String urlString, Object tag) throws
IOException {
ResponseBody body = getOkHttpClientUtils(context).buildResponseBody(urlString, tag);
if (body != null) {
return body.bytes();
}
return null;
}
/**
* 作用:實(shí)現(xiàn)網(wǎng)絡(luò)訪問(wèn)文件端蛆,將獲取到的數(shù)據(jù)存在字符串中
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @return String
*/
public static String getStringFromURL(Context context, String urlString, Object tag) throws
IOException {
ResponseBody body = getOkHttpClientUtils(context).buildResponseBody(urlString, tag);
if (body != null) {
return body.string();
}
return null;
}
///////////////////////////////////////////////////////////////////////////
// POST方式訪問(wèn)網(wǎng)絡(luò)
///////////////////////////////////////////////////////////////////////////
/**
* 基方法凤粗,返回Request對(duì)象
*
* @param urlString
* @param tag
* @return
*/
private Request buildPostRequest(String urlString, RequestBody requestBody, Object tag) {
Request.Builder builder = new Request.Builder();
builder.url(urlString).post(requestBody);
//builder.addHeader("Accept", "application/json; q=0.5");
if (tag != null) {
builder.tag(tag);
}
return builder.build();
}
/**
* 作用:post提交數(shù)據(jù),返回服務(wù)器端返回的字節(jié)數(shù)組
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @return byte[]
*/
private String postRequestBody(String urlString, RequestBody requestBody, Object tag) {
Request request = buildPostRequest(urlString, requestBody, tag);
try {
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:POST提交鍵值對(duì)今豆,再返回相應(yīng)的數(shù)據(jù)
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @param map :訪問(wèn)url時(shí)嫌拣,需要傳遞給服務(wù)器的鍵值對(duì)數(shù)據(jù)。
* @return String
*/
public static String postKeyValuePair(Context context, String urlString, Map<String, String>
map, Object tag) {
//往FormEncodingBuilder對(duì)象中放置鍵值對(duì)
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
}
//生成請(qǐng)求體對(duì)象
RequestBody requestBody = formBuilder.build();
//將請(qǐng)求提放置到請(qǐng)求對(duì)象中
return getOkHttpClientUtils(context).postRequestBody(urlString, requestBody, tag);
}
/**
* 作用:POST提交Json字符串呆躲,再返回相應(yīng)的數(shù)據(jù)
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @param jsonString :訪問(wèn)url時(shí)异逐,需要傳遞給服務(wù)器的json字符串
* @return byte[]
*/
public static String postJsonString(Context context, String urlString, String jsonString,
Object tag) {
//定義mimetype對(duì)象
/*String MEDIA_TYPE_STREAM = "application/octet-stream;charset=utf-8";
String MEDIA_TYPE_STRING = "text/plain;charset=utf-8";*/
String MEDIA_TYPE_JSON = "application/json;charset=utf-8";
MediaType JSON = MediaType.parse(MEDIA_TYPE_JSON);
RequestBody requestBody = RequestBody.create(JSON, jsonString);
return getOkHttpClientUtils(context).postRequestBody(urlString, requestBody, tag);
}
///////////////////////////////////////////////////////////////////////////
// 異步網(wǎng)絡(luò)訪問(wèn)
///////////////////////////////////////////////////////////////////////////
/**
* 開啟異步線程訪問(wèn)網(wǎng)絡(luò),通過(guò)回調(diào)方法實(shí)現(xiàn)數(shù)據(jù)加載
* 如果第二個(gè)參數(shù)為null插掂,空callback灰瞻, 則說(shuō)明不在意返回結(jié)果
*
* @param urlString
* @param callback
*/
public static void getDataAsync(Context context, String urlString, Callback callback, Object
tag) {
Request request = getOkHttpClientUtils(context).buildGetRequest(urlString, tag);
getOkHttpSingletonInstance().newCall(request).enqueue(callback);
}
/**
* 作用:post提交數(shù)據(jù),返回服務(wù)器端返回的字節(jié)數(shù)組
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
*/
private void postRequestBodyAsync(String urlString, RequestBody requestBody, Callback
callback, Object tag) {
Request request = buildPostRequest(urlString, requestBody, tag);
if (callback == null) {
new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
}
};
}
mOkHttpClient.newCall(request).enqueue(callback);
}
/**
* 作用:POST提交鍵值對(duì),再返回相應(yīng)的數(shù)據(jù)
*
* @param urlString :訪問(wèn)網(wǎng)絡(luò)的url地址
* @param map :訪問(wèn)url時(shí)箩祥,需要傳遞給服務(wù)器的鍵值對(duì)數(shù)據(jù)院崇。
*/
public static void postKeyValuePairAsync(Context context, String urlString, Map<String,
String> map, Callback callback, Object tag) {
//往FormEncodingBuilder對(duì)象中放置鍵值對(duì)
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
}
//生成請(qǐng)求體對(duì)象
RequestBody requestBody = formBuilder.build();
//將請(qǐng)求提放置到請(qǐng)求對(duì)象中
getOkHttpClientUtils(context).postRequestBodyAsync(urlString, requestBody, callback, tag);
}
/**
* 作用:post異步上傳文件,提交分塊請(qǐng)求
*
* @param urlString 網(wǎng)絡(luò)地址
* @param map 提交給服務(wù)器的表單信息鍵值對(duì)
* @param files 提交的文件
* @param formFieldName 每個(gè)需要提交的文件對(duì)應(yīng)的文件input的name值
* @param callback 異步上傳回調(diào)方法
* @throws IOException
*/
public static void postUploadFilesAsync(Context context, String urlString, Map<String,
String> map, File[] files, String[] formFieldName, Callback callback, Object tag)
throws IOException {
RequestBody requestBody = getOkHttpClientUtils(context).buildRequestBody(map, files,
formFieldName);
getOkHttpClientUtils(context).postRequestBodyAsync(urlString, requestBody, callback, tag);
}
///////////////////////////////////////////////////////////////////////////
// POST方式提交分塊請(qǐng)求袍祖,實(shí)現(xiàn)文件上傳
///////////////////////////////////////////////////////////////////////////
/**
* 同步基于post的文件上傳:上傳多個(gè)文件以及攜帶key-value對(duì):主方法
*
* @param urlString
* @param formFiledName
* @param files
* @param map
* @param tag
* @return String
* @throws IOException
*/
public static String postUploadFiles(Context context, String urlString, Map<String, String>
map, File[] files, String[] formFiledName, Object tag) throws IOException {
RequestBody requestBody = getOkHttpClientUtils(context).buildRequestBody(map, files,
formFiledName);
return getOkHttpClientUtils(context).postRequestBody(urlString, requestBody, tag);
}
/**
* 創(chuàng)建post上傳附件的request對(duì)象
* Post方式提交分塊請(qǐng)求——上傳文件及其它表單數(shù)據(jù)
*
* @param files
* @param formFiledName
* @param map
* @return
*/
private RequestBody buildRequestBody(Map<String, String> map, File[] files, String[]
formFiledName) {
MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
//往MultipartBuilder對(duì)象中添加普通input控件的內(nèi)容
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
//添加普通input塊的數(shù)據(jù)
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry
.getKey() + "\""),
RequestBody.create(null, entry.getValue()));
}
}
//往MultipartBuilder對(duì)象中添加file input控件的內(nèi)容
if (files != null && formFiledName != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
String fileName = file.getName();
RequestBody requestBody = RequestBody.create(MediaType.parse
("multipart/form-data"), file);
//添加file input塊的數(shù)據(jù)
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + formFiledName[i] + "\"; filename=\"" + fileName +
"\""), requestBody);
}
}
//生成RequestBody對(duì)象
return builder.build();
}
/**
* 獲取Mime類型
*
* @param filename
* @return
*/
private static String getMimeType(String filename) {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(filename);
if (contentTypeFor == null) {
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
public static void cancelCall(Object tag) {
getOkHttpSingletonInstance().cancel(tag);
}
}
CSDN請(qǐng)移步到