Question

I am sending a multipart request to a server which will include an image, as well as a couple of strings. I haven't found any guide on how to get this done, all i have found are just how to make post and get and put etc, but nothing on multipart. I would be glad for any help, thanks

Était-ce utile?

La solution

Here you have a example to do declare it using a @Rest interface and here you have a example to do it using Spring Android (used by AA to generate the client class)

All together you can use something like this (this code is not tested):

@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(); } } }

Autres conseils

Try this:

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

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

then:

   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
   }

I use three libraries for that:

  • httpcore-4.3.jar
  • httpmime-4.3.1.jar
  • apache-mime4j-0.4.jar

check that: http://hc.apache.org/downloads.cgi, I think the latter is not here, look elsewhere.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top