我正在尝试将图片发送到我的API。但是在使用MultipartEntity StringBody时,由于不推荐使用StringBody(String),我会收到错误。
我不工作。我是Android sending image to Server via MultipartEntity - setting Content-type?的样本。
这是代码:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("api_key", api_key));
params.add(new BasicNameValuePair("access_token", access_token));
API api = new API(mApiKey, mApiSecret);
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("MY API URL");
File file = new File(imagePath);
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
StringBody api_key = new StringBody(mApiKey);
StringBody access_token = new StringBody(access_token);
entity.addPart("api_key", api_key);
entity.addPart("hash", access_token);
entity.addPart("image", contentFile);
postMethod.setEntity(entity);
client.execute(postMethod);
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:16)
不推荐使用用于创建StringBody
的新实例的构造函数。
而不是
new StringBody(mApiKey);
你应该使用StringBody
构造函数和第二个参数ContentType
new StringBody(mApiKey, ContentType.TEXT_PLAIN);
有关详细信息,请参阅:
和
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/ContentType.html
答案 1 :(得分:2)
StringBody:
entity.addPart("api_key", new StringBody(mApiKey,ContentType.TEXT_PLAIN));
MultipartEntity: