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

Android Java应用调用Python后端接口出现308错误求助

解决Android Volley请求返回308错误的方案

核心问题分析

308状态码代表永久重定向(Permanent Redirect),结合你的代码和场景,主要存在两个关键问题:

1. GsonRequest构造参数误用

你的GsonRequest构造函数第三个参数定义为请求头headers,但调用时却传入了要提交的用户数据userObject——相当于把本该放在请求体的JSON数据当成HTTP请求头发送,服务器无法正确解析请求,进而返回重定向错误。

2. URL路径可能缺少末尾斜杠

多数Python后端框架(如Flask、Django)会对不带末尾斜杠的路径自动返回308重定向,指向带斜杠的路径(比如/user → /user/)。


具体修复步骤

步骤1:修正GsonRequest的实现与调用

首先调整GsonRequest,使其支持将Java对象序列化为JSON请求体:

public class GsonRequest<T> extends Request<T> {
    private final Gson gson = new Gson();
    private final Class<T> responseClass;
    private final Object requestBody;
    private final Response.Listener<T> listener;

    // 适配请求体与响应类型的构造函数
    public GsonRequest(int method, String url, Object requestBody, Class<T> responseClass,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.requestBody = requestBody;
        this.responseClass = responseClass;
        this.listener = listener;
        // 设置正确的JSON请求头
        setHeader("Content-Type", "application/json");
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        // 将请求体对象序列化为JSON字节数组
        return gson.toJson(requestBody).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers)
            );
            return Response.success(
                    gson.fromJson(json, responseClass),
                    HttpHeaderParser.parseCacheHeaders(response)
            );
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }
}

然后修正RegisterActivity中的调用逻辑,传入正确的请求体和响应类型:

private void register() {
    final String user = username.getText().toString();
    final String pass = password.getText().toString();
    Map<String, String> userObject = new HashMap<>();
    userObject.put("username", user);
    userObject.put("password", pass);
    final int method = Request.Method.POST;
    // 添加末尾斜杠,适配后端重定向规则
    final String url = "https://tddd80-app-joneri.azurewebsites.net/user/";

    // 创建GsonRequest,指定响应类型为String(可根据后端返回调整)
    GsonRequest<String> request = new GsonRequest<>(
            Request.Method.POST,
            url,
            userObject,
            String.class,
            response -> System.out.println("Success! Response: " + response),
            error -> System.out.println("Error with request: " + error.getMessage())
    );

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(request);
}

步骤2:处理Volley的308重定向支持

Volley默认逻辑可能未正确支持POST请求的308重定向,若调整URL后仍有问题,可自定义HurlStack开启自动重定向:

RequestQueue requestQueue = Volley.newRequestQueue(this, new HurlStack() {
    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection connection = super.createConnection(url);
        // 允许自动跟随重定向
        connection.setInstanceFollowRedirects(true);
        return connection;
    }
});

验证建议

  1. 用Postman或curl分别测试https://tddd80-app-joneri.azurewebsites.net/user和https://tddd80-app-joneri.azurewebsites.net/user/,确认哪个能正常接收POST请求。
  2. 检查请求的Content-Type是否为application/json,确保后端能正确解析JSON请求体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:24:56