2014-12-05 1112 views
7

我想發送圖像到我的API。但同時使用MultipartEntity StringBody我得到錯誤作爲StringBody(字符串)已棄用。Android StringBody(字符串)已被棄用

我不工作。我是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(); 
} 

回答

16

您使用創建的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

+0

另外,該類型MultipartEntity已被棄用。 – Joolah 2014-12-05 08:03:54

+0

是的,可以通過Google輕鬆找到文檔:http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html – Thorben 2014-12-05 09:01:55