【问题标题】:Volley requests not working with Django SessionsVolley 请求不适用于 Django 会话
【发布时间】:2017-03-27 00:41:51
【问题描述】:

我在服务器上运行了一个 Django 脚本,它为发送到服务器的每个请求创建会话变量。该脚本根据之前存储的会话变量返回一个特定的值。

当我在浏览器上测试脚本时,Django 上的会话按要求工作。

但是,当使用 Volley 发送相同的请求时,脚本会将每个请求视为一个新请求,而不考虑以前的会话变量。

    StringRequest stringRequest = new StringRequest(Request.Method.GET,Send_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Response(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    requestQueue.add(stringRequest);
}

RequestQueue defined globally and context assigned in the onCreate() method

P.S 我通过浏览器请求重新检查,它可以工作。所以 Django End 上没有问题。
谢谢!

【问题讨论】:

  • 您是否在后端进行了corsfilter之类的事情?使用 spring 框架开发后端时,我遇到了同样的问题。

标签: android django session android-volley


【解决方案1】:

Volley 默认不支持 Cookie。您应该覆盖StringRequest 类,如下所示:

public class StringRequest extends com.android.volley.toolbox.StringRequest {

private final Map<String, String> _params;

/**
 * @param method
 * @param url
 * @param params
 *            A {@link HashMap} to post with the request. Null is allowed
 *            and indicates no parameters will be posted along with request.
 * @param listener
 * @param errorListener
 */
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
        ErrorListener errorListener) {
    super(method, url, listener, errorListener);

    _params = params;
}

@Override
protected Map<String, String> getParams() {
    return _params;
}

/* (non-Javadoc)
 * @see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    // since we don't know which of the two underlying network vehicles
    // will Volley use, we have to handle and store session cookies manually
    MyApp.get().checkSessionCookie(response.headers);

    return super.parseNetworkResponse(response);
}

/* (non-Javadoc)
 * @see com.android.volley.Request#getHeaders()
 */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    MyApp.get().addSessionCookie(headers);

    return headers;
}
}

和你的应用程序类:

public class MyApp extends Application {
    private static final String SET_COOKIE_KEY = "Set-Cookie";
    private static final String COOKIE_KEY = "Cookie";
    private static final String SESSION_COOKIE = "sessionid";

    private static MyApp _instance;
  private RequestQueue _requestQueue;
  private SharedPreferences _preferences;

    public static MyApp get() {
        return _instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        _instance = this;
            _preferences = PreferenceManager.getDefaultSharedPreferences(this);
        _requestQueue = Volley.newRequestQueue(this);
    }

    public RequestQueue getRequestQueue() {
        return _requestQueue;
    }


    /**
     * Checks the response headers for session cookie and saves it
     * if it finds it.
     * @param headers Response Headers.
     */
    public final void checkSessionCookie(Map<String, String> headers) {
        if (headers.containsKey(SET_COOKIE_KEY)
                && headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
                String cookie = headers.get(SET_COOKIE_KEY);
                if (cookie.length() > 0) {
                    String[] splitCookie = cookie.split(";");
                    String[] splitSessionId = splitCookie[0].split("=");
                    cookie = splitSessionId[1];
                    Editor prefEditor = _preferences.edit();
                    prefEditor.putString(SESSION_COOKIE, cookie);
                    prefEditor.commit();
                }
            }
    }

    /**
     * Adds session cookie to headers if exists.
     * @param headers
     */
    public final void addSessionCookie(Map<String, String> headers) {
        String sessionId = _preferences.getString(SESSION_COOKIE, "");
        if (sessionId.length() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append(SESSION_COOKIE);
            builder.append("=");
            builder.append(sessionId);
            if (headers.containsKey(COOKIE_KEY)) {
                builder.append("; ");
                builder.append(headers.get(COOKIE_KEY));
            }
            headers.put(COOKIE_KEY, builder.toString());
        }
    }

}

您也可以查看this link 了解更多...

【讨论】:

    【解决方案2】:

    我在其他脚本语言中使用 volley library 时遇到了同样的问题,你需要通过 about volley library here ..

    默认情况下额外存储缓存值,因此您的代码第二次无法工作(这意味着返回相同的值

    因此您可以尝试HttpURLConnection 默认方法来使用此类服务​​器操作。

    谢谢希望它的帮助!!!

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2014-10-09
      • 2013-03-02
      相关资源
      最近更新 更多