使用Android通过JSON上传照片到服务器
问题描述:
我正尝试将照片上传到我的服务器。但是我对如何以JSON提交多部分请求感到困惑。这是我迄今为止的代码。使用Android通过JSON上传照片到服务器
// Set up HTTP client.
HttpClient client = DefaultHttpClient();
// Multi-part content body.
MultipartEntity mpEntity = new MultipartEntity();
ContentBody content = new FileBody(source, "image/jpeg");
mpEntity.addPart("user[photo]", content);
// Put method.
HttpPut method = new HttpPut(url);
method.setHeader("Accept", "application/json");
method.setHeader("Content-type", "application/json");
method.setHeader("Accept-Encoding", "gzip");
method.setEntity(mpEntity);
response = client.execute(method);
// Result.
HttpEntity responseEntity = response.getEntity();
我从我的Rails服务器得到的错误是:
所有的Error occurred while parsing request parameters.
Contents: [garbled data]
答
这适用于Rails服务器。
// Target URL.
// Add '.json' to end of the URL. This will make Rails
// accept the request as JSON but yet allow the multi-part content
// encoding below.
String url = "http://blahblah.com/users/123.json"
// Set up HTTP client.
HttpClient client = DefaultHttpClient();
// Multi-part content body.
MultipartEntity mpEntity = new MultipartEntity();
ContentBody content = new FileBody(source, "image/jpeg");
mpEntity.addPart("user[photo]", content);
// Put method.
HttpPut method = new HttpPut(url);
method.setEntity(mpEntity);
response = client.execute(method);
// Result.
HttpEntity responseEntity = response.getEntity();
工程!
答
首先,这是不特定的Android在所有。这属于HTTP相关的问题。我会回答它。
使用application/json
内容类型不能发送多部分http消息。您应该在消息中使用适当的多部分内容类型。虽然在你的例子中你只传递一个部分,所以在技术上不需要多部分。但是,这取决于您的Rails服务器作为请求的期望。
弗拉基米尔。我想出了一种实际使其工作的方法。你是对的,我不能为'application/json'设置头文件。但我可以在URL级别设置它,Rails服务器将接受它。我会在下面发布一个适当的答案。 – colinwong 2012-03-01 22:05:47