mercredi 25 février 2015

Not able to POST to REST API

Today I'm making my first attempt of sending a POST request with a JSON to save some data, and I'm not being able to do so. My app works by signing in, and then save, modify and delete data. It's already done in iOS, but since I'm new to Android, I'm not sure how to do it. Here's my POST function:



public String POST(String targetURL, String urlParameters, String user, String pwd) {
URL url;
String u = targetURL;

HttpURLConnection connection = null;
try {
// Create connection
// u=URLEncoder.encode(u, "UTF-8");
url = new URL(u);
connection = (HttpURLConnection) url.openConnection();
// cambiarlo luego al usuario q esta logeado
String login = user + ":" + pwd;
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 " + encoding);
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 request
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();
}
}
}


The method above is executed with Asynctask, and even if I use it to Login using Spring security, it works, and even I can save for internal usage the username, password, and secret token. I dunno if I need to put the token in a header or something, because I already did that, with no positive results. I'm supposing that the only permission I need to execute this is the internet one, so in my manifest file I specified that permission. I'm going crazy with this issue, please help! Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire