Android 服务器未读取HttpClient向RESTful API发布数据
我尝试向RestFul服务(带有Rest框架的django)发送Http post。GET方法很好,但POST方法给我带来了问题。我认为可能是凭证问题或字符串格式问题。以下是Android REST客户端代码Android 服务器未读取HttpClient向RESTful API发布数据,android,django,rest,django-rest-framework,androidhttpclient,Android,Django,Rest,Django Rest Framework,Androidhttpclient,我尝试向RestFul服务(带有Rest框架的django)发送Http post。GET方法很好,但POST方法给我带来了问题。我认为可能是凭证问题或字符串格式问题。以下是Android REST客户端代码 HttpPost request = new HttpPost(urlString); String encoding = Base64 .encodeToString(new String("username":"pass
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应用程序日志:
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"}].
[Webservice: {"detail": "Authentication credentials were not provided."}]
如果我省略setHeader(“授权”)部分,它将给我
[Webservice: {"detail": "Invalid username/password"}].
[Webservice: {"detail": "Authentication credentials were not provided."}]
尝试下面的代码..将下面的代码放入您的活动类中
class PlaceOrder extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPst = new HttpPost(
"yout_url");
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(
2);
parameters.add(new BasicNameValuePair("username", "apple"));
parameters.add(new BasicNameValuePair("pw", "apple"));
parameters.add(new BasicNameValuePair("email",
"apple@gmail.com"));
parameters.add(new BasicNameValuePair("name", "apple"));
httpPst.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpRes = httpClient.execute(httpPst);
String str = convertStreamToString(
httpRes.getEntity().getContent()).toString();
Log.i("mlog", "outfromurl" + str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
class PlaceOrder扩展了异步任务{
@凌驾
受保护的Void doInBackground(Void…参数){
//TODO自动生成的方法存根
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost httpPst=新的HttpPost(
“yout_url”);
ArrayList参数=新建ArrayList(
2);
添加(新的BasicNameValuePair(“用户名”、“苹果”);
添加(新的BasicNameValuePair(“pw”、“apple”);
添加(新的BasicNameValuePair(“电子邮件”),
"apple@gmail.com"));
添加(新的BasicNameValuePair(“名称”、“苹果”);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse httpRes=httpClient.execute(httpPst);
字符串str=convertStreamToString(
httpRes.getEntity().getContent()).toString();
Log.i(“mlog”、“outfromurl”+str);
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}
}
公共静态字符串convertStreamToString(InputStream为){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(例外e){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
并调用
newplaceorder().execute()代码>从uronCreate方法我通过更改解码密码的代码解决了这个问题
String encoding = Base64
.encodeToString(new String("username":"password")
.getBytes(), Base64.URL_SAFE|Base64.NO_WRAP);
这个logcat基本上就是完整的logcat。这段android代码将在主活动的onCreate()中的Asynctask中运行。我还尝试在另一个api上使用GET方法(不需要用户名/密码),效果很好。我无法理解你的日志…谢谢你的帮助。对不起,把logcat弄糊涂了。我印了两行。第一行是JSONObject.toString()。第二行是Django Rest服务器的响应。是的,正确的响应是混淆我更新了问题。谢谢,谢谢。我一到家就会试试,让你知道。谢谢!六羟甲基三聚氰胺六甲醚。。。它不起作用。输出:I/mlog﹕ outfromurl{“用户名”:[“此字段是必需的。”],“电子邮件”:[“此字段是必需的。”],“pw”:[“此字段是必需的。”],“名称”:[“此字段是必需的。”]}