Android中的StringBody(String)已被弃用。

7

我试图向我的API发送一张图片。但是在使用MultipartEntity StringBody时,我收到了一个StringBody(String)已弃用的错误。

它无法工作。我在Android通过MultipartEntity将图像发送到服务器 - 设置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();
}
2个回答

16

您用来创建新实例StringBody的构造函数已被弃用。

取而代之的是

new StringBody(mApiKey);

你应该使用带有第二个参数的 StringBody 构造函数,该参数是一个 ContentType,例如:

你应该使用带有第二个参数的 StringBody 构造函数,该参数是一个 ContentType,例如

new StringBody(mApiKey, ContentType.TEXT_PLAIN);

如需更多信息,请查看:

http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/content/StringBody.html

以及

http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/ContentType.html


同时,MultipartEntity 类型已被弃用。 - Thiago
是的,文档可以很容易地通过谷歌找到:http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html - Thorben

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接