You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Volley调用API抛出AuthFailureError(403 Forbidden)问题求助

Android Volley调用更新用户API时出现认证失败错误

开发一款具备EditText编辑用户数据功能的App:EditText初始加载用户对象数据正常,用户修改后点击按钮调用API更新数据,但API抛出Volley认证失败错误。该API在Postman中可正常请求,仅在Android端调用时出现认证失败问题。

调试响应说明

  • Postman请求成功响应
  • Android端返回认证失败响应

核心代码

NetworkAPICall.kt

import android.app.Activity
import android.content.Intent
import android.util.Log
import com.android.volley.*
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.softnoesis.maxotexmart.login.LoginActivity
import com.softnoesis.maxotexmart.utils.AppPreference
import com.softnoesis.maxotexmart.utils.CommonUtils
import com.softnoesis.maxotexmart.utils.Constant.Companion.NETWORK_API_CALL
import com.softnoesis.maxotexmart.utils.Constant.Companion.TAG
import org.json.JSONObject
import java.lang.reflect.Type

class NetworkAPICall {
    fun CallApplicationWS(mContext: Activity?, NetworkAPICallModel: NetworkAPICallModel,
                          NetworkAPIResponseCallback: NetworkAPIResponseCallback?) {
        Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS")
        if (NetworkAPICallModel.getCommonUtils().isNetworkAvailable(mContext!!)) try {
            if (!NetworkAPICallModel.isShowProgress())
                NetworkAPICallModel.getCommonUtils().showProgress(mContext)
            val RequestQueue: RequestQueue = Volley.newRequestQueue(mContext)
            val StringRequest: StringRequest = object : StringRequest(NetworkAPICallModel.getRequest_type(),
                NetworkAPICallModel.getApiURL(), Response.Listener<String?> { response ->
                Log.i(TAG, "$NETWORK_API_CALL --> " +
                        "CallApplicationWS --> response")
                try{
                    NetworkAPICallModel.getCommonUtils().hideProgress()
                    if(NetworkAPICallModel.getParserType() != null) {
                        val `object`: Any = Gson().fromJson(response, NetworkAPICallModel.getParserType())
                        NetworkAPICallModel.setResponseObject(`object`)
                    }
                    NetworkAPIResponseCallback?.onSuccessResponse(JSONObject(response), NetworkAPICallModel)
                } catch(jsonException: Exception) {
                    NetworkAPICallModel.getCommonUtils().hideProgress()
                    Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS --> response --> ${jsonException.message}")
                    try{
                        NetworkAPICallModel.getCommonUtils().hideProgress()
                    }catch (e: Exception) {
                        NetworkAPICallModel.getCommonUtils().hideProgress()
                        Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS --> response --> ${e.message}")
                    }
                }
            },
                Response.ErrorListener { error ->
                    NetworkAPICallModel.getCommonUtils().hideProgress()
                    Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS --> error --> ${error.message}")
                    val response: NetworkResponse = error.networkResponse
                    if (error is ServerError) {
                        try {
                            val intent = Intent(mContext, LoginActivity::class.java)
                            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
                            mContext.startActivity(intent)
                        } catch (e1: Exception) {
                            NetworkAPICallModel.getCommonUtils().hideProgress()
                            Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS --> error --> ${e1.message}")
                        }
                    }
                    CommonUtils().hideProgress()
                    CommonUtils().showDialog(
                        mContext,
                        """
                                            Something went wrong! Please try again later!
                                            If problem still persist, please drop mail at support@.com
                                            """.trimIndent()
                    ).show()
            }) {
                override fun getParams(): MutableMap<String, String> {
                    var params: MutableMap<String, String> = HashMap()
                    val type: Type = object : TypeToken<HashMap<String, String>>() {}.type
                    params = Gson().fromJson(NetworkAPICallModel.getJsonObjectRequest().toString(), type)
                    return params
                }

                override fun getHeaders(): MutableMap<String, String> {
                    val params: MutableMap<String, String> = HashMap()
//                     headers.put("Authorization", "Bearer " + jetEncryptor.getJwtkey());
                    if (AppPreference(mContext).isUserLogin()) {
                        params["Authorization"] = "Bearer " + AppPreference(mContext).getToken()
                    }
                    return params
                }
            }
            RequestQueue.add(StringRequest)
            StringRequest.retryPolicy = DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
            )
        } catch (e: Exception) {
            NetworkAPICallModel.getCommonUtils().hideProgress()
            Log.i(TAG, "$NETWORK_API_CALL --> CallApplicationWS -->${e.message}")
        } else {
            NetworkAPICallModel.getCommonUtils().hideProgress()
            CommonUtils().showDialog(mContext, "Please check you internet connection").show()
        }
    }
}

参数传递代码

try {
    val mJsObjParam = JSONObject()
    mJsObjParam.put("company_name", userData1.user?.companyName ?: "")
    mJsObjParam.put("owner_name", userData1.user?.ownerName ?: "")
    mJsObjParam.put("owner_phone", userData1.user?.phone ?: "")
    mJsObjParam.put("owner_whatsapp_number", userData1.user?.ownerWhatsappNumber ?: "")
    mJsObjParam.put("address", userData1.user?.address ?: "")
    
    val parserType = object : TypeToken<EditUserResponse?>() {}.type
    val networkAPICallModel = NetworkAPICallModel(
        APIConstants.EDIT_USER_URL,
        APIConstants.POST_REQUEST,
        mJsObjParam
    )
    networkAPICallModel.setParserType(parserType)
    mNetworkAPICall!!.CallApplicationWS(mContext as Activity?, networkAPICallModel, this)
} catch (e: Exception) {
    mCommonUtils?.hideProgress()
    Log.i(
        Constant.TAG,
        "${Constant.USER_PRESENTER} --> addUser --> Exception --> ${e.printStackTrace()}"
    )
}

内容的提问来源于stack exchange,提问作者user2357113

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:25:19