compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.zhy:okhttputils:2.6.2'
compile 'com.google.code.gson:gson:2.7'
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Call;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 类 名 : OkHttpClientManager
* 更 新 者: $Author$
* 更新时间: $Date$
* 描 述 : ${TODO}
*/
public class OkHttpClientManager {
private static OkHttpClientManager mInstance;
private OkHttpClient mOkHttpClient;
private Handler mDelivery;
private Gson mGson;
private static final String TAG = "OkHttpClientManager";
private OkHttpClientManager() {
mOkHttpClient = new OkHttpClient();
mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);//设置读取超时时间
mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);//设置写的超时时间
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
mDelivery = new Handler(Looper.getMainLooper());
mGson = new Gson();
}
public static OkHttpClientManager getInstance() {
if (mInstance == null) {
synchronized (OkHttpClientManager.class) {
if (mInstance == null) {
mInstance = new OkHttpClientManager();
}
}
}
return mInstance;
}
/**
* 同步的Get请求
*
* @param url
* @return Response
*/
private Response _getAsyn(String url) throws IOException {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response execute = call.execute();
return execute;
}
/**
* 同步的Get请求
*
* @param url
* @return 字符串
*/
private String _getAsString(String url) throws IOException {
Response execute = _getAsyn(url);
return execute.body().string();
}
/**
* 异步的get请求
*
* @param url
* @param callback
*/
private void _getAsyn(String url, final ResultCallback callback) {
final Request request = new Request.Builder()
.url(url)
.build();
deliveryResult(callback, request);
}
/**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return
*/
private Response _post(String url, Param... params) throws IOException {
Request request = buildPostRequest(url, params);
Response response = mOkHttpClient.newCall(request).execute();
return response;
}
/**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return 字符串
*/
private String _postAsString(String url, Param... params) throws IOException {
Response response = _post(url, params);
return response.body().string();
}
/**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
private void _postAsyn(String url, final ResultCallback callback, Param... params) {
Request request = buildPostRequest(url, params);
deliveryResult(callback, request);
}
/**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
private void _postAsyn(String url, final ResultCallback callback, Map<String, String> params) {
Param[] paramsArr = map2Params(params);
Request request = buildPostRequest(url, paramsArr);
deliveryResult(callback, request);
}
/**
* 同步基于post的文件上传
*
* @param params
* @return
*/
private Response _post(String url, File[] files, String[] fileKeys, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, File file, String fileKey) throws IOException {
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, File file, String fileKey, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
return mOkHttpClient.newCall(request).execute();
}
/**
* 异步基于post的文件上传
*
* @param url
* @param callback
* @param files
* @param fileKeys
* @throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, files, fileKeys, params);
deliveryResult(callback, request);
}
/**
* 异步基于post的文件上传,单文件不带参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException {
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
deliveryResult(callback, request);
}
/**
* 异步基于post的文件上传,单文件且携带其他form参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @param params
* @throws IOException
*/
private void _postAsyn(String url, ResultCallback callback, File file, String fileKey, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
deliveryResult(callback, request);
}
/**
* 异步下载文件
*
* @param url
* @param destFileDir 本地文件存储的文件夹
* @param callback
*/
private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) {
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
sendFailedStringCallback(request, e, callback);
}
@Override
public void onResponse(Response response) {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
File file = new File(destFileDir, getFileName(url));
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径
sendSuccessResultCallback(file.getAbsolutePath(), callback);
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
}
}
}
});
}
private String getFileName(String path) {
int separatorIndex = path.lastIndexOf("/");
return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
}
private void setErrorResId(final ImageView view, final int errorResId) {
mDelivery.post(new Runnable() {
@Override
public void run() {
view.setImageResource(errorResId);
}
});
}
//*************对外公布的方法************
public static Response getAsyn(String url) throws IOException {
return getInstance()._getAsyn(url);
}
public static String getAsString(String url) throws IOException {
return getInstance()._getAsString(url);
}
public static void getAsyn(String url, ResultCallback callback) {
getInstance()._getAsyn(url, callback);
}
public static Response post(String url, Param... params) throws IOException {
return getInstance()._post(url, params);
}
public static String postAsString(String url, Param... params) throws IOException {
return getInstance()._postAsString(url, params);
}
public static void postAsyn(String url, final ResultCallback callback, Param... params) {
getInstance()._postAsyn(url, callback, params);
}
public static void postAsyn(String url, final ResultCallback callback, Map<String, String> params) {
getInstance()._postAsyn(url, callback, params);
}
public static Response post(String url, File[] files, String[] fileKeys, Param... params) throws IOException {
return getInstance()._post(url, files, fileKeys, params);
}
public static Response post(String url, File file, String fileKey) throws IOException {
return getInstance()._post(url, file, fileKey);
}
public static Response post(String url, File file, String fileKey, Param... params) throws IOException {
return getInstance()._post(url, file, fileKey, params);
}
public static void postAsyn(String url, ResultCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException {
getInstance()._postAsyn(url, callback, files, fileKeys, params);
}
public static void postAsyn(String url, ResultCallback callback, File file, String fileKey) throws IOException {
getInstance()._postAsyn(url, callback, file, fileKey);
}
public static void postAsyn(String url, ResultCallback callback, File file, String fileKey, Param... params) throws IOException {
getInstance()._postAsyn(url, callback, file, fileKey, params);
}
public static void displayImage(final ImageView view, String url, int errorResId) throws IOException {
// getInstance()._displayImage(view, url, errorResId);
}
public static void displayImage(final ImageView view, String url) {
// getInstance()._displayImage(view, url, -1);
}
public static void downloadAsyn(String url, String destDir, ResultCallback callback) {
getInstance()._downloadAsyn(url, destDir, callback);
}
//****************************
private Request buildMultipartFormRequest(String url, File[] files,
String[] fileKeys, Param[] params) {
params = validateParam(params);
MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM);
for (Param param : params) {
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
RequestBody.create(null, param.value));
}
if (files != null) {
RequestBody fileBody = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
String fileName = file.getName();
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
fileBody);
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private String guessMimeType(String path) {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null) {
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
private Param[] validateParam(Param[] params) {
if (params == null)
return new Param[0];
else return params;
}
private Param[] map2Params(Map<String, String> params) {
if (params == null) return new Param[0];
int size = params.size();
Param[] res = new Param[size];
Set<Map.Entry<String, String>> entries = params.entrySet();
int i = 0;
for (Map.Entry<String, String> entry : entries) {
res[i++] = new Param(entry.getKey(), entry.getValue());
}
return res;
}
private static final String SESSION_KEY = "Set-Cookie";
private static final String mSessionKey = "JSESSIONID";
private Map<String, String> mSessions = new HashMap<String, String>();
private void deliveryResult(final ResultCallback callback, Request request) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
sendFailedStringCallback(request, e, callback);
}
@Override
public void onResponse(final Response response) {
try {
final String string = response.body().string();
if (callback.mType == String.class) {
sendSuccessResultCallback(string, callback);
} else {
Object o = mGson.fromJson(string, callback.mType);
sendSuccessResultCallback(o, callback);
}
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} catch (com.google.gson.JsonParseException e)//Json解析的错误
{
sendFailedStringCallback(response.request(), e, callback);
}
}
});
}
private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null)
callback.onError(request, e);
}
});
}
private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onResponse(object);
}
}
});
}
private Request buildPostRequest(String url, Param[] params) {
if (params == null) {
params = new Param[0];
}
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Param param : params) {
builder.add(param.key, param.value);
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
public static abstract class ResultCallback<T> {
Type mType;
public ResultCallback() {
mType = getSuperclassTypeParameter(getClass());
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
public abstract void onError(Request request, Exception e);
public abstract void onResponse(T response);
}
public static class Param {
public Param(String timeStamp, long time) {
}
public Param(String key, String value) {
this.key = key;
this.value = value;
}
String key;
String value;
}
}
//
public class ResultJson {
//接口url
private static String baseUrl = "";
//商户密钥
private static String signature = "";
//退款秘钥
private static String refundKey = "";
//定义一个接口
public interface onPaySucessListener {
void OnPaySucessListener(String ResultCode);
}
public void CreateOrderAndPay(String payNo, String terminalTransNO, List<ProductInfo> list, final onPaySucessListener paySucessListener) {
long time = System.currentTimeMillis() / 1000;
String sendJson = "[";
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
sendJson += String.format("{\"ProductName\":\"%s\"," + "\"ProductPrice\":%s,\"ProductCount\":%d,\"ProductID\":%d,"
+ "\"ProductTypeId\":%d,\"ProductType\":\"%s\"},",
list.get(i).getProductName(), list.get(i).getProductPrice(),
list.get(i).getProductCount(), list.get(i).getProductID(),
list.get(i).getProductID(), list.get(i).getProductType()
);
}
}
sendJson = sendJson.substring(0, sendJson.length() - 1);
sendJson += "]";
OkHttpClientManager.Param[] parm = new OkHttpClientManager.Param[]{
new OkHttpClientManager.Param("MerchantCode", "S201706002"),//商户号, TODO
new OkHttpClientManager.Param("terminalNo", "S2017060021000700"),//终端编号
new OkHttpClientManager.Param("payNo", payNo),//TODO 支付码
new OkHttpClientManager.Param("payType", "1"),//支付类型
new OkHttpClientManager.Param("parkId", "S201706002"),
new OkHttpClientManager.Param("terminalTransNO", terminalTransNO),//TODO 定单号随机生成
new OkHttpClientManager.Param("postOrder", sendJson),//产品明显
new OkHttpClientManager.Param("signature", getSignature("S201706002", time)),
new OkHttpClientManager.Param("OrderAmount", "0.01"),//订单总额 TODO
new OkHttpClientManager.Param("TerminalType", "1"),//总端类型 TODO
new OkHttpClientManager.Param("TimeStamp", time + ""),
new OkHttpClientManager.Param("ProductType", "1"),
new OkHttpClientManager.Param("terminalId", "S2017060021000700"),//终端遍号
new OkHttpClientManager.Param("str2", "")
};
OkHttpClientManager.getInstance().postAsyn(baseUrl + "CreateOrderAndPay",//
new OkHttpClientManager.ResultCallback<String>() {
@Override
public void onError(Request request, Exception e) {
Log.d("onError==", e.getMessage().toString());
}
@Override
public void onResponse(String response) {
Log.e("result====", response);
if (response.indexOf("{") < 0) {
return;
}
String strJson = response.substring(response.indexOf("{"), response.length());
strJson = strJson.replace("</string>", "");
Log.e("strJson====", strJson);
Gson gson = new Gson();
ObjModeBean bean = gson.fromJson(strJson, ObjModeBean.class);
if (bean.IsTrue) {
// String resultJson = bean.ResultJson;
// Log.e("resultJson:", resultJson);
// List<PaySucessBean> paySucessBeen = gson.fromJson(bean.ResultJson, new TypeToken<List<PaySucessBean>>() {
// }.getType());
String ResultCode = bean.ResultCode;
if (paySucessListener != null) {
paySucessListener.OnPaySucessListener(ResultCode);
}
}
}
}, parm);
Gson gson = new Gson();
String json = gson.toJson(parm);
Log.d("请求参数的json数据==", json);
}
//获取加密后的签名参数
private static String getSignature(String mSignatre, long time) {
//商户号+秘钥+当前时间戳用MD5加密就是signature
String sign = mSignatre + signature + time;
String s = Md5utils.Md5(sign);
return s;
}
public void ApplyRefundService(String OrderNo, List<ProductInfo> list) {
String refundUrl = baseUrl + "ApplyRefundService";
long time = System.currentTimeMillis() / 1000;
String sendJson = "[";
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
sendJson += String.format("{\"ProductName\":\"%s\"," + "\"ProductPrice\":%s,\"ProductCount\":%d,\"ProductID\":%d,"
+ "\"ProductTypeId\":%d,\"ProductType\":\"%s\"},",
list.get(i).getProductName(), list.get(i).getProductPrice(),
list.get(i).getProductCount(), list.get(i).getProductID(),
list.get(i).getProductID(), list.get(i).getProductType()
);
}
}
sendJson = sendJson.substring(0, sendJson.length() - 1);
sendJson += "]";
OkHttpClientManager.Param[] parms = new OkHttpClientManager.Param[]{
new OkHttpClientManager.Param("MerchantCode", "S201706002"),//商户号,
new OkHttpClientManager.Param("OrderNo", OrderNo),//定单号
new OkHttpClientManager.Param("RefundTotal", "0.01"),//退款总金额
new OkHttpClientManager.Param("RefundDetails", sendJson),//退款详情
new OkHttpClientManager.Param("UserId", "123012"),//用户ID
new OkHttpClientManager.Param("Remark", ""),//备注
new OkHttpClientManager.Param("KeySing", refundKey),//秘钥
new OkHttpClientManager.Param("TimeStamp", time + ""),//时间戳
new OkHttpClientManager.Param("terminalId", "S2017060021000700"),//终端遍号
new OkHttpClientManager.Param("str2", "")
};
OkHttpClientManager.getInstance().postAsyn(refundUrl, new OkHttpClientManager.ResultCallback<String>() {
@Override
public void onError(Request request, Exception e) {
Log.d("RefundonError==", e.getMessage().toString());
}
@Override
public void onResponse(String response) {
Log.d("RefundonResponse==", response);
}
}, parms);
Gson gson = new Gson();
String json = gson.toJson(parms);
Log.d("ApplyRefundService==", json);
}
}
使用:
mResultJson = new ResultJson();
mResultJson.CreateOrderAndPay(qrCode, "123456789012", mList, this);
webservice数据解析
最新推荐文章于 2024-09-05 16:42:41 发布