【问题标题】:Can't send POST request in android to Grails backend无法在 android 中将 POST 请求发送到 Grails 后端
【发布时间】:2015-03-25 16:55:00
【问题描述】:

我在使用 Grails 和 SpringSecurity 向后端发送 POST 时遇到了一点问题。 我不知道为什么,但是当我发送 ROLE_ADMIN 方法时,它不起作用。我尝试对用户和密码进行编码并将其设置在请求标头上并尝试相同但没有编码。 我真的开始对这个问题感到绝望。 这是我的 POST 代码:

public String POST2(String targetURL, String urlParameters, String user,
            String clave) {
        URL url;
        String h = "http://";
        String u = h+targetURL;

        HttpURLConnection connection = null;
        try { // Create connection //
            // targetURL = URLEncoder.encode(targetURL, "UTF-8");
            url = new URL(u);
            connection = (HttpURLConnection) url.openConnection(); // cambiarlo
                                                                    // luego al
                                                                    // usuario q
            String login = user + ":" + clave;
            String encoding = new String(org.apache.commons.codec.binary.Base64 //
                    .encodeBase64(org.apache.commons.codec.binary.StringUtils //
                            .getBytesUtf8(login)));

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Basic " + login);
            connection.setRequestProperty("Content-Type", "plain/text");// hace
                                                                        // // q
            // sirva // con // el // string // de // json

            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(120000); // Send
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            // Get Response 
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            this.setResponseCode(connection.getResponseCode());
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    }

这就是我所说的:

private class EntrenadorExecutioner extends AsyncTask<String, Void, String> {
        private EntrenadorActivity activity = null;

        public EntrenadorExecutioner(EntrenadorActivity activity) {
            attach(activity);
        }

        private void attach(EntrenadorActivity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            activity.startLoader();
        }

        @Override
        protected String doInBackground(String... params) {
            String json = "";

            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.accumulate("cedula", params[0]);
                jsonObject.accumulate("nombre", params[1]);
                jsonObject.accumulate("primerApellido", params[2]);
                jsonObject.accumulate("segundoApellido", params[3]);

                json = jsonObject.toString();
            } catch (JSONException je) {
                je.printStackTrace();
            }

            return rh.POST2(Constantes.GUARDAR_ENTRENADOR, json,
                    Constantes.user.getUsername(),
                    Constantes.user.getPassword());
        }

        @Override
        protected void onPostExecute(String response) {
            activity.markAsDone();
            if (response.equals("")) {
                // Refresh the list view then show success
                Toast.makeText(getApplicationContext(),
                        getString(R.string.successEntre), Toast.LENGTH_SHORT)
                        .show();
            } else
                Toast.makeText(getApplicationContext(),
                        getString(R.string.err_unexp), Toast.LENGTH_LONG)
                        .show();
        }
    }

【问题讨论】:

  • 一件事:当我向登录 api 发送 POST 请求时,它确实返回了用户、编码密码甚至令牌,它只是不适用于其余服务
  • 请发布一些logcat 输出。什么不工作?有例外吗?请发布的不仅仅是您的代码。
  • 对不起,我有点新……没有例外或类似的东西,我得到的输出实际上是处理 Web 应用程序登录的 html 页面
  • 就是这样!这应该告诉您您的身份验证失败并且您被重定向到登录页面,或者类似的东西。
  • 其实没那么简单,因为实际上是为 iPhone 版本的应用程序工作的,如果我去一个 REST 客户端,使用相同的数据,它确实会登录:/跨度>

标签: android spring security grails


【解决方案1】:

我找到了解决方案! 我需要做的就是使用 Grails 用户令牌,并将其添加到标题中,如下所示:

connection.setRequestProperty("Authorization", "Bearer " + Constantes.user.getToken()); // where get token returns the auth token

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2020-05-09
    • 2019-06-04
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多