如何获得XSRF-TOKEN&用HttpUrlConnections Post方法发送它

时间:2016-03-17 06:48:17

标签: android post spring-security android-networking

我能够通过Cookies获取XSRF令牌但是当我在HttpsUrlConnection的Post方法中使用该令牌时它给了我405即方法不允许错误

final String COOKIES_HEADER = "Set-Cookie";


  Map<String, List<String>> headerFields = connection.getHeaderFields();
            List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

            if (cookiesHeader != null) {

                for (String cookie : cookiesHeader) {
                    Log.d("Rjcookies", HttpCookie.parse(cookie).get(0).getName());
                    if (HttpCookie.parse(cookie).get(0).getName().equals("XSRF-TOKEN")) {
                        Log.d("Rjcookie", HttpCookie.parse(cookie).get(0).getValue());
                        xsrf = HttpCookie.parse(cookie).get(0).getValue();
                        new RequestTask().execute();

                       /* new FetchSecuredResourceTask().execute();*/
                        return  HttpCookie.parse(cookie).get(0).getValue();

                    }


                }
            }

在POST方法中我使用该标记

connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                /*connection.setRequestProperty("Content-Length", "" +
                        Integer.toString(urlParameters.getBytes().length));*/
               /* connection.setRequestProperty("Content-Language","en-US");*/
                /*connection.setRequestProperty("X-Login-Ajax-call","true");*/
                connection.setRequestProperty("X-XSRF-TOKEN",xsrf);
                connection.setRequestProperty("charset", "utf-8");
                connection.setRequestProperty("Accept","*/*");
                connection.setUseCaches (true);
                connection.setDoInput(true);
                connection.setDoOutput(true);


                //Send request
                DataOutputStream wr = new DataOutputStream (
                        connection.getOutputStream ());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();
 Log.d("Rj_wr", String.valueOf(connection.getResponseCode()));
                InputStream is = null;
                //Get Response
                if (connection.getResponseCode() == 200) {
                    is = connection.getInputStream();
                } else {
     /* error from server */
                    is = connection.getErrorStream();
                }

0 个答案:

没有答案