我在我的 Android 应用程序中使用带有服务的 drupal,当我使用用户名和密码连接到 REST 服务器时,我得到 200 的响应,这没问题,但是当我尝试创建节点时,它返回 401 错误。
我正在使用 HttpClient,我应该关心设置 cookie 还是有什么问题?登录并保持创建节点或用户的身份验证的正确方法是什么......等等。
有什么建议或想法吗?
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();
}
}
编辑解决方案: 最后,问题出在drupal方面,您应该在设置服务器时检查会话身份验证,在我的情况下是休息:)所以,现在我相信,httpClient会自动管理cookies。