我正在尝试将照片上传到我的服务器。但我对如何以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]
答案 0 :(得分:0)
首先,这根本不是特定于Android的。这属于与HTTP相关的问题。我会回答它。
您无法使用application/json
内容类型发送多部分http消息。您应该在邮件中使用适当的多部分内容类型。虽然在你的例子中你只传递了一个部分,所以技术上不需要多部分。但是,这取决于您的Rails服务器期望的请求。
答案 1 :(得分:-2)
这适用于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();
作品!