I’m using drupal with services from my Android app, when I connect to REST server with a user name and password I get response of 200 which is OK, but when I’m trying to create a node, it returns 401 error.
I’m using HttpClient, should I care about the setting the cookies or what is the problem?
What is the correct way to login and keep the authentication for creating node or users …etc.
Any suggestions or ideas?
HttpResponse response = null;
HttpPost postRequest = null;
HttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(
"http://192.168.1.104/?q=rest/user/login");
String loginString=String.format("{\"username\":\"%s\",\"password\":\"%s\"}", "user","pass");
Log.d("expression",loginString);
StringEntity input = new StringEntity(nodeText );
input.setContentType("application/json");
postRequest.setEntity(input);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// here is the code to create a node
try {
HttpPost postRequest2 = new HttpPost(
"http://192.168.1.104/?q=rest/node");
String nodeText= String.format( "{\"type\":\"story\",\"title\":\" %s \",\"body\":\" %s \"}", title,"");
Log.d("expression",nodeText);
StringEntity input = new StringEntity(nodeText );
input.setContentType("application/json");
postRequest2.setEntity(input);
response = httpClient.execute(postRequest2);
if (response.getStatusLine().getStatusCode() != 201) {
}
System.out.println(response.getStatusLine().getStatusCode());
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDITED FOR SOLUTION:
finally, the problem was from the drupal side, you should check the session authentication while setting up your server, in my case it is rest 🙂 so, now I believe that, httpClient automatically manage the cookies.
It seems likely that you need the cookie.
You usually get the cookie as a response from your login method. Get it, store it and pull it out and stick it in the headers of the
HttpPostala: