无法将 android 中的 POST 请求发送到 Grails 后端
Can't send POST request in android to Grails backend
我在向我的后端发送 POST 时遇到一点问题,它是使用 Grails 和 SpringSecurity 制作的。
我不知道为什么,但是当我发送 ROLE_ADMIN 方法时,它不起作用。我已经尝试对用户和密码进行编码并根据请求 header 进行设置并尝试相同但没有编码。
我真的开始对这个问题感到绝望。
这是我的 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();
}
}
我找到了解决办法!
我所需要做的就是使用 Grails 用户令牌,并将其添加到 headers,如下所示:
connection.setRequestProperty("Authorization", "Bearer " + Constantes.user.getToken()); // where get token returns the auth token
我在向我的后端发送 POST 时遇到一点问题,它是使用 Grails 和 SpringSecurity 制作的。 我不知道为什么,但是当我发送 ROLE_ADMIN 方法时,它不起作用。我已经尝试对用户和密码进行编码并根据请求 header 进行设置并尝试相同但没有编码。 我真的开始对这个问题感到绝望。 这是我的 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();
}
}
我找到了解决办法! 我所需要做的就是使用 Grails 用户令牌,并将其添加到 headers,如下所示:
connection.setRequestProperty("Authorization", "Bearer " + Constantes.user.getToken()); // where get token returns the auth token