我正在构建一个 Android 客户端应用程序来连接到 Django 服务器。这里的问题是我无法登录到我的服务器:(。怎么了,帮帮我:| 这是我的 loginFunction():
创建一个 DefaultHttpClient:
DefaultHttpClient httpClientStatic = new DefaultHttpClient();
从服务器获取 crsf 的函数:
public String getCsrfFromUrl(String url) { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClientStatic.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); List<Cookie> cookies = httpClientStatic.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.e("COOKIES GET ", "Empty Cookies"); } else { for (int i = 0; i < cookies.size(); i++) { Log.e("COOKIES GET ", cookies.get(i).getName()+"--"+cookies.get(i).getValue()); } } return cookies.get(0).getValue(); }
将用户名、传递、crsf 发布到服务器的功能:
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { // Making HTTP GET request to get csrfmiddlewaretoken: try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); Log.e("JSON", "In login user 02.4"); HttpResponse httpResponse = httpClientStatic.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); ..... //Next is read respone, and return json type }
登录功能:
public JSONObject loginUser(String username, String password){ // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(loginURL); params.add(new BasicNameValuePair("csrfmiddlewaretoken", csrfmiddlewaretoken)); JSONObject json = jsonParser.getJSONFromUrl(loginURL, params); return json; }
它仍然返回 401 错误 anh 500 状态:|。