2014-01-23 31 views
3

我正在向服務器發送多部分請求,該服務器將包含圖像以及一些字符串。 我還沒有找到任何關於如何完成這個任務的指南,我發現的只是如何讓帖子和獲取和放等,但沒有多部分。 我會很高興的任何幫助,感謝使用@Rest在Android註釋中創建多部分帖子

回答

5

Here你有一個例子做使用@Rest接口和here你有一個例子使用Spring的Android(由AA用於生成客戶端類)

總之,你可以使用的東西做聲明它像這樣的(此代碼未測試):

@Rest(rootUrl = "http://mycompany.com/images", converters = FormHttpMessageConverter.class) public interface RestClient { @Post("/loadimage") void sendImage(MultiValueMap formfields); } @EActivity public class MyActivity extends Activity { @RestService RestClient restClient; //Inject it void sendImage(InputStream in) { MultiValueMap values = new org.springframework.util.LinkedMultiValueMap<String,Object>(); try { values.put("fileName", "a.jpg"); values.put("file", in); restClient.sendImage(values); } finally { in.close(); } } }

+0

第二個鏈接指向春天例子是不是一個鏈接,你可以添加鏈接? –

+0

已經修復,對不起。 – jmvivo

+0

謝謝,這很有幫助:) –

0

試試這個:

String url = "here_your_url"; 
    File image = new File("here_your_image's_route"); 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost  = new HttpPost(url); 

則:

MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); 

    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
    multipartEntity.addPart("image", new FileBody(image)); 

    final HttpEntity requestEntity = multipartEntity.build(); 

    //You can add more HttpEntity 
    httpPost.setEntity(requestEntity); 

    HttpResponse response = httpClient.execute(httpPost); 

    StatusLine statusLine = response.getStatusLine(); 
    int statusCode  = statusLine.getStatusCode(); 

    if(statusCode == HttpStatus.SC_OK) { 
     //everything is correct 
    } else { 
     //something has gone wrong 
    } 

我用三個庫爲:

  • 的HttpCore-4.3。罐子
  • httpmime-4.3.1.jar
  • Apache的mime4j-0.4.jar

檢查:http://hc.apache.org/downloads.cgi,我認爲後者是不是在這裏,看看其他地方。