/**
* Date:2016年9月7日下午10:37:11
* Copyright (c) 2016, www.bwbroad.com All Rights Reserved.
*
*/
package tools;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 基于okhttp3的工具类 <br/>
* Date: 2016年9月7日 下午10:37:11 <br/>
* 基本用法:<br/>
* Http3 http=new Http3(); <br/>
* String s= http.getString("www.baidu.com");<br/>
*
* @author xuejianxin
*/
public class Http3 {
private static final int TYPE_BYTE = 1;
private static final int TYPE_STRING = 0;
private int loadTimes;
private int maxLoadTimes = 3;
private OkHttpClient client = null;
private Headers headers = null;
private Headers.Builder hb = new Headers.Builder();
public Http3() {
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).build();
}
/**
*
* 设置header<br/>
* Date: 2016年9月12日 下午9:23:23 <br/>
*
* @author xuejianxin
* @param headersParams
*/
public void setHeaders(Map<String, String> headersParams) {
if (headersParams != null) {
Iterator<String> iterator = headersParams.keySet().iterator();
String key = "";
while (iterator.hasNext()) {
key = iterator.next().toString();
hb.add(key, headersParams.get(key));
}
}
headers = hb.build();
}
/**
*
* Get 请求 返回string<br/>
* Date: 2016年9月12日 下午5:16:14 <br/>
*
* @author xuejianxin
* @param url
* @return
*/
public final byte[] getBytes(final String url) {
Request.Builder requestBuilder = new Request.Builder().url(url);
return (byte[]) call(requestBuilder, TYPE_BYTE);
}
/**
*
* Get 请求返回 bytes[]<br/>
* Date: 2016年9月12日 下午5:16:32 <br/>
*
* @author xuejianxin
* @param url
* @return
*/
public final String getString(final String url) {
Request.Builder requestBuilder = new Request.Builder().url(url);
return (String) call(requestBuilder, TYPE_STRING);
}
/**
*
* post请求 返回 byte<br/>
* Date: 2016年9月12日 下午5:16:55 <br/>
*
* @author xuejianxin
* @param url
* @param parameters
* @return
*/
public final byte[] postFormBytes(final String url,
final Map<String, String> parameters) {
return (byte[]) post(url, parameters, TYPE_BYTE);
}
/**
*
* post请求 返回 string<br/>
* Date: 2016年9月12日 下午5:16:55 <br/>
*
* @author xuejianxin
* @param url
* @param parameters
* 参数
* @return
*/
public final String postFormString(final String url,
final Map<String, String> parameters) {
return (String) post(url, parameters, TYPE_STRING);
}
/**
*
* 带附件的请求<br/>
* Date: 2016年9月12日 下午5:18:52 <br/>
*
* @author xuejianxin
* @param url
* @param parameters
* @param resultType
* @return
*/
public final Object postMultipart(final String url,
final Map<String, String> parameters, Map<String, File> files,
final int resultType) {
MultipartBody.Builder mb = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
MediaType jpg = MediaType.parse("image/jpg");
for (Map.Entry<String, String> en : parameters.entrySet()) {
mb.addFormDataPart(en.getKey(), en.getValue());
}
for (Map.Entry<String, File> en : files.entrySet()) {
mb.addFormDataPart(en.getKey(), en.getKey(),
RequestBody.create(jpg, en.getValue()));
}
MultipartBody multipartBody = mb.build();
Request.Builder requestBuilder = new Request.Builder().url(url).post(
multipartBody);
return call(requestBuilder, resultType);
}
/**
*
* 普通post 请求<br/>
* Date: 2016年9月12日 下午5:18:12 <br/>
*
* @author xuejianxin
* @param url
* @param parameters
* @param resultType
* @return
*/
private final Object post(final String url,
final Map<String, String> parameters, final int resultType) {
FormBody.Builder fb = new FormBody.Builder();
for (Map.Entry<String, String> en : parameters.entrySet()) {
fb.add(en.getKey(), en.getValue());
}
RequestBody formBody = fb.build();
Request.Builder requestBuilder = new Request.Builder().url(url).post(
formBody);
return call(requestBuilder, resultType);
}
private final Object call(Request.Builder requestBuilder,
final int resultType) {
if (null != headers) {
requestBuilder.headers(headers);
}
Request request = requestBuilder.build();
ArrayBlockingQueue<Object> result = new ArrayBlockingQueue<Object>(1);
loadTimes = 0;
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (e.getCause().equals(SocketTimeoutException.class)
&& loadTimes < maxLoadTimes)// 如果超时并未超过指定次数,则重新连接
{
loadTimes++;
client.newCall(call.request()).enqueue(this);
} else {
call.cancel();// 努力半天白费了 取消本次请求
e.printStackTrace();
}
}
@Override
public void onResponse(Call call, Response response)
throws IOException {
ResponseBody responseBody = null;
try {
responseBody = response.body();
if (response.isSuccessful()) {
Object o = null;
if (resultType == TYPE_STRING) {
o = responseBody.string();
result.put(o);
} else if (resultType == TYPE_BYTE) {
o = responseBody.bytes();
result.put(o);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != responseBody) {
responseBody.close();
}
}
}
});
try {
// return result.take();
return result.poll(10, TimeUnit.SECONDS);// 一定要设置超时
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
}
okhttp3基本用法
最新推荐文章于 2024-08-18 15:06:56 发布