Commit 10b5b968 authored by 赵鹏翔's avatar 赵鹏翔

网络请求相关代码整理

parent 4e50bc6e
......@@ -59,7 +59,6 @@ public class LFilePickerActivity extends BaseActivity {
private List<File> mListFiles;
private ArrayList<String> mListNumbers = new ArrayList<String>();//存放选中条目的数据地址
private String mQrCodeEncodeMsg;
private byte[] dialogLock = new byte[0];
@Override
protected void onCreate(Bundle savedInstanceState) {
......@@ -270,30 +269,18 @@ public class LFilePickerActivity extends BaseActivity {
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse(""), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("logFile", file.getName(), requestBody);
String ip = getDataSourceIp(selfCashierTerminalConfig,
ApiService.Companion.getUPLOAD_LOG_FILE() + "?equType=" + equType);
String ip = ApiConfig.INSTANCE.getDataSourceIp(selfCashierTerminalConfig, equType);
if (!TextUtils.isEmpty(selfCashierTerminalConfig.getScoRuntimeConfig().getPlatformUrl())) {
ip = selfCashierTerminalConfig.getScoRuntimeConfig().getPlatformUrl()
+ ApiService.Companion.getUPLOAD_LOG_FILE();
}
LogUtils.e("ip = " + ip);
//防止文件过大 导致OOM 30M
// long size = file.length();
// if (size > 34307335) {
// ToastUtils.showLong("日志文件过大");
// LogFileUtils.INSTANCE.setProhibitWrite(false);
// hidProgressDialog();
// return;
// }
tryGenQrCodeMsg(file.getName());
ApiRequest.Companion.getInstance().uploadFile(ip, part,
new CommonCallback<Object>() {
new CommonCallback<String>() {
@Override
public void onSuccess(Object data) {
public void onSuccess(String data) {
hidProgressDialog();
LogFileUtils.INSTANCE.setProhibitWrite(false);
successToast = Toasty.success(LFilePickerActivity.this, "文件上传成功!");
......@@ -310,17 +297,6 @@ public class LFilePickerActivity extends BaseActivity {
});
}
public static String getDataSourceIp(@NonNull SelfCashierTerminalConfig selfCashierTerminalConfig, @NonNull String path) {
if (selfCashierTerminalConfig == null
|| selfCashierTerminalConfig.getScoRuntimeConfig() == null
) {
throw new RuntimeException("DataSourceIpUtils SelfCashierTerminalConfig is null");
}
return TextUtils.isEmpty(selfCashierTerminalConfig.getScoRuntimeConfig().getErpIp()) ?
ApiConfig.getBaseUrl() + path :
selfCashierTerminalConfig.getScoRuntimeConfig().getErpIp() + path;
}
@NonNull
private String getEquType() {
String equType = "";
......
package com.miya.fastcashier.net
import android.text.TextUtils
import com.miya.fastcashier.BuildConfig
import com.miya.fastcashier.net.ApiConfig
import com.miya.fastcashier.beans.SelfCashierTerminalConfig
object ApiConfig {
private const val BASE_URL = "https://hhms.miyapay.com/"
......@@ -12,4 +13,22 @@ object ApiConfig {
get() = if (BuildConfig.ISTEST) {
BASE_URL_4_TEST
} else BASE_URL
fun getAuthorization(token: String): String {
return "bearer $token"
}
fun getDataSourceIp(
selfCashierTerminalConfig: SelfCashierTerminalConfig,
equType: String
): String? {
if (selfCashierTerminalConfig?.scoRuntimeConfig == null) {
throw RuntimeException("DataSourceIpUtils SelfCashierTerminalConfig is null")
}
val path = "${ApiService.UPLOAD_LOG_FILE}?equType=$equType"
return if (TextUtils.isEmpty(selfCashierTerminalConfig.scoRuntimeConfig.erpIp)) (baseUrl + path)
else selfCashierTerminalConfig.scoRuntimeConfig.erpIp + path
}
}
\ No newline at end of file
......@@ -59,7 +59,7 @@ class ApiRequest private constructor() {
fun uploadFile(
url: String,
part: MultipartBody.Part,
commonCallback: CommonCallback<Object>
commonCallback: CommonCallback<String>
) {
getApiService().uploadFile(url, part).enqueue(commonCallback)
}
......
......@@ -6,11 +6,16 @@ import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.http.*
/**
* 请求地址配置
*/
interface ApiService {
companion object {
/**
* 登录
*/
const val LOGIN: String = "verify/auth/token"
/**
......@@ -24,17 +29,10 @@ interface ApiService {
}
}
@POST(LOGIN)
fun login(@Body loginRequestCall: LoginRequest): Call<BaseResponse<SelfCashierAccountInfo>>
/**
* 上传日志文件
*
* @param file
* @return
*/
@Multipart
@POST
fun uploadFile(@Url url: String?, @Part part: MultipartBody.Part): Call<BaseResponse<Object>>
fun uploadFile(@Url url: String?, @Part part: MultipartBody.Part): Call<BaseResponse<String>>
}
\ No newline at end of file
......@@ -2,7 +2,9 @@ package com.miya.fastcashier.net
import java.io.Serializable
/**
* 接口请求后返回的基础response
*/
data class BaseResponse<T>(val code: String, val msg: String, val data: T) : Serializable {
fun isSuccess(): Boolean {
......
package com.miya.fastcashier.net;
import android.util.Log;
import com.miya.fastcashier.BaseApplication;
import com.miya.fastcashier.R;
import com.miya.fastcashier.utils.BaseFunctionKt;
import java.net.SocketTimeoutException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* 类描述:通用请求返回
* 创建人:zpxiang
* 创建时间:
* 修改人:
* 修改时间:
*/
public abstract class CommonCallback<T> implements Callback<BaseResponse<T>> {
private static final String RESPONSE_MSG_UNKNOW = "未知异常";
private static final String CALLBACK_SUCCEED_CODE = "200";
interface ErrorType {
int ERROR_TYPE_CUSTOM = 0;
int ERROR_TYPE_HTTP = 1;
int ERROR_TYPE_EXCEPTION = 2;
}
interface ResponseCode {
String RESPONSE_CODE_FAILED = String.valueOf(-1); // 返回数据失败
String RESPONSE_CODE_NETWORK_DISCONNECT = String.valueOf(-2); // 无网络
String RESPONSE_CODE_NETWORK_TIMEOUT = String.valueOf(-3); // 超时
}
@Override
public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
if (response.isSuccessful() && response.body() != null) {
String responseCode = response.body().getCode(); // 业务自定义Code
if (CALLBACK_SUCCEED_CODE.equals(responseCode)) {
onSuccess(response.body().getData());
} else {
onFailure(ErrorType.ERROR_TYPE_CUSTOM,
responseCode,
response.body().getError());
}
} else if (response.errorBody() != null) {
onFailure(ErrorType.ERROR_TYPE_HTTP,
String.valueOf(response.code()),
response.errorBody().toString());
} else {
onFailure(ErrorType.ERROR_TYPE_HTTP,
ResponseCode.RESPONSE_CODE_FAILED,
RESPONSE_MSG_UNKNOW); // 理论上不会存在此种情况
}
}
@Override
public void onFailure(Call<BaseResponse<T>> call, Throwable t) {
String temp = t.getMessage();
Log.e("#### HttpLog", "请求失败:" + temp);
String errorMessage;
if (!BaseFunctionKt.isNetworkConnected(BaseApplication.Companion.getApplication())) {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_network_error);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_NETWORK_DISCONNECT, errorMessage);
return;
}
if (t instanceof SocketTimeoutException) {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_network_timeout);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_NETWORK_TIMEOUT, errorMessage);
} else {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_data_error);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_FAILED, errorMessage);
}
}
public abstract void onSuccess(T data);
public abstract void onFailure(int errorType, String errorCode, String errorMessage);
}
package com.miya.fastcashier.net
import android.util.Log
import com.miya.fastcashier.BaseApplication.Companion.getApplication
import com.miya.fastcashier.R
import com.miya.fastcashier.utils.isNetworkConnected
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.SocketTimeoutException
/**
* 类描述:通用请求返回
* 创建人:zpxiang
* 创建时间:
* 修改人:
* 修改时间:
*/
abstract class CommonCallback<T> : Callback<BaseResponse<T>?> {
companion object {
private const val RESPONSE_MSG_UNKNOW = "未知异常"
private const val CALLBACK_SUCCEED_CODE = "200"
}
internal interface ErrorType {
companion object {
const val ERROR_TYPE_CUSTOM = 0
const val ERROR_TYPE_HTTP = 1
const val ERROR_TYPE_EXCEPTION = 2
}
}
internal interface ResponseCode {
companion object {
val RESPONSE_CODE_FAILED: String = "-1" // 返回数据失败
val RESPONSE_CODE_NETWORK_DISCONNECT: String = "-2" // 无网络
val RESPONSE_CODE_NETWORK_TIMEOUT: String = "-3" // 超时
}
}
override fun onResponse(call: Call<BaseResponse<T>?>, response: Response<BaseResponse<T>?>) {
if (response.isSuccessful && response.body() != null) {
val responseCode = response.body()!!.code // 业务自定义Code
if (CALLBACK_SUCCEED_CODE == responseCode) {
onSuccess(response.body()!!.data)
} else {
onFailure(
ErrorType.ERROR_TYPE_CUSTOM,
responseCode,
response.body()!!.getError()
)
}
} else if (response.errorBody() != null) {
onFailure(
ErrorType.ERROR_TYPE_HTTP, response.code().toString(),
response.errorBody().toString()
)
} else {
onFailure(// 理论上不会存在此种情况
ErrorType.ERROR_TYPE_HTTP,
ResponseCode.RESPONSE_CODE_FAILED,
RESPONSE_MSG_UNKNOW
)
}
}
override fun onFailure(call: Call<BaseResponse<T>?>, t: Throwable) {
val temp = t.message
Log.e("#### HttpLog", "请求失败:$temp")
val errorMessage: String
if (!isNetworkConnected(getApplication())) {
errorMessage = getApplication().getString(R.string.common_prompt_network_error)
onFailure(
ErrorType.ERROR_TYPE_EXCEPTION,
ResponseCode.RESPONSE_CODE_NETWORK_DISCONNECT,
errorMessage
)
return
}
if (t is SocketTimeoutException) {
errorMessage = getApplication().getString(R.string.common_prompt_network_timeout)
onFailure(
ErrorType.ERROR_TYPE_EXCEPTION,
ResponseCode.RESPONSE_CODE_NETWORK_TIMEOUT,
errorMessage
)
} else {
errorMessage = getApplication().getString(R.string.common_prompt_data_error)
onFailure(
ErrorType.ERROR_TYPE_EXCEPTION,
ResponseCode.RESPONSE_CODE_FAILED,
errorMessage
)
}
}
abstract fun onSuccess(data: T)
abstract fun onFailure(errorType: Int, errorCode: String?, errorMessage: String?)
}
\ No newline at end of file
package com.miya.fastcashier.net;
import com.miya.fastcashier.beans.SelfCashierAccountInfo;
import com.miya.fastcashier.service.AccountService;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* 签名拦截器
* 添加请求头校验 AUTHORIZATION
*/
public class RequestSignInterceptor implements Interceptor {
private static final String AUTHORIZATION = "Authorization";
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
String requestUrl = original.url().toString();
Request.Builder requestBuilder = original.newBuilder();
SelfCashierAccountInfo accountInfo = AccountService.INSTANCE.getAccountInfo();
if (accountInfo != null && accountInfo.getAccessToken() != null) {
String loginUrl = ApiService.Companion.wrapUrl(ApiService.LOGIN);
if (!requestUrl.equals(loginUrl)) {
requestBuilder.addHeader(AUTHORIZATION, "bearer " + accountInfo.getAccessToken().getAccessToken());
}
}
Request request = requestBuilder.build();
return chain.proceed(request);
}
}
package com.miya.fastcashier.net
import com.miya.fastcashier.net.ApiConfig.getAuthorization
import com.miya.fastcashier.net.ApiService.Companion.wrapUrl
import com.miya.fastcashier.service.AccountService.getAccountInfo
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
/**
* 签名拦截器
* 添加请求头校验 AUTHORIZATION
*/
class RequestSignInterceptor : Interceptor {
companion object {
private const val AUTHORIZATION = "Authorization"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val original: Request = chain.request()
val requestUrl = original.url.toString()
val requestBuilder: Request.Builder = original.newBuilder()
val accountInfo = getAccountInfo()
if (accountInfo != null && accountInfo.accessToken != null) {
val loginUrl = wrapUrl(ApiService.LOGIN)
if (requestUrl != loginUrl) {
requestBuilder.addHeader(
AUTHORIZATION,
getAuthorization(accountInfo.accessToken.accessToken)
)
}
}
val request: Request = requestBuilder.build()
return chain.proceed(request)
}
}
\ No newline at end of file
......@@ -31,12 +31,11 @@ class LoginViewModel : ViewModel() {
override fun onFailure(
errorType: Int,
errorCode: String,
errorMessage: String
errorCode: String?,
errorMessage: String?
) {
loginLiveData.postValue(Result.failure(RuntimeException(errorMessage)))
}
})
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment