【发布时间】:2014-08-08 13:44:46
【问题描述】:
我尝试向 RestFul 服务(带有 Rest Framework 的 django)发布 Http 帖子。 GET 方法工作正常,但 POST 方法给我带来了问题。我认为这可能是凭证问题或字符串格式问题。这是 Android REST 客户端代码。
HttpPost request = new HttpPost(urlString);
String encoding = Base64
.encodeToString(new String("username":"password")
.getBytes(), Base64.DEFAULT);
request.setHeader("Authorization", "Basic " + encoding);
request.setHeader("Content-type", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "apple");
obj.put("pw", "apple");
obj.put("email", "apple@gmail.com");
obj.put("name", "apple");
System.out.println(obj.toString());
StringEntity entity = new StringEntity(obj.toString());
entity.setContentType("application/json");
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
// Get the status of web service
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("Status Line", "Webservice: " + line);
}
这是 Android aplog:
I/System.out﹕ {"email":"apple@gmail.com","username":"apple","name":"apple","pw":"apple"}
D/Status Line﹕ Webservice: {"username": ["This field is required."], "email": ["This field is required."], "pw": ["This field is required."], "name": ["This field is required."]}
这是来自 Django 服务器的日志:
[05/Aug/2014 15:09:39] "POST /split/api_post_user/ HTTP/1.1" 400 151
我也尝试过 CURL,以下脚本运行良好。
curl -u username:password -X POST \
--data '{"username" : "apple" , "pw" : "12345", "email" : "abc@gmail.com", "name" : "John" }' \
-H "Content-Type:application/json" \
$URL
logcat 的第二行是来自服务器的响应。 例如,如果我使用了错误的用户/密码对。它会给我
[Webservice: {"detail": "Invalid username/password"}].
如果我省略 setHeader("Authorization") 部分,它会给我
[Webservice: {"detail": "Authentication credentials were not provided."}]
【问题讨论】:
-
那个logcat基本上就是完整的logcat。这段 android 代码将在主要活动的 onCreate() 中的 Asynctask 中运行。我还尝试在另一个 api 上执行 GET 方法(不需要用户名/密码),它工作正常。
-
我无法理解你的日志
-
嗯...感谢您的帮助。对不起,令人困惑的 logcat。我打印了两行。第一行是 JSONObject.toString()。第二行是来自 Django Rest 服务器的响应。
-
是的,正确的反应令人困惑
-
我更新了问题。谢谢。
标签: android django rest django-rest-framework androidhttpclient