【问题标题】:Android StringBody(String) is deprecatedAndroid StringBody(String) 已弃用
【发布时间】:2015-02-03 08:01:07
【问题描述】:

我正在尝试将图像发送到我的 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();
}

【问题讨论】:

    标签: java android apache http post


    【解决方案1】:

    用于创建StringBody 的新实例的构造函数已弃用。

    代替

    new StringBody(mApiKey);
    

    您应该使用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

    【讨论】:

    【解决方案2】:

    字符串体:

     entity.addPart("api_key", new StringBody(mApiKey,ContentType.TEXT_PLAIN));
    

    多部分实体:

    检查:The type MultipartEntity is deprecated

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2016-10-16
      • 2013-07-18
      • 2012-12-25
      • 2021-08-31
      • 2015-09-18
      相关资源
      最近更新 更多