无法在Android中向Grails后端发送POST请求

时间:2015-03-25 16:55:01

标签: android spring security grails

我在向后端发送POST时遇到一些问题,这是使用Grails和SpringSecurity完成的。 我不知道为什么,但是当我发送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();
        }
    }

1 个答案:

答案 0 :(得分:0)

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

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