Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a large file in multipart using OkHttp

What are my options for uploading a single large file (more specifically, to s3) in multipart in Android using OKhttp?

like image 901
Tomer Weller Avatar asked Jun 18 '14 07:06

Tomer Weller


People also ask

What is OkHttp used for?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

Why do we use OkHttp in Android?

OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.

What is MultipartBody?

MultipartBody : used while breaking up the data in a POST request into different discrete types and send to server.


1 Answers

From the OkHttp Recipes page, this code uploads an image to Imgur:

private static final String IMGUR_CLIENT_ID = "..."; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");  private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {   // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image   RequestBody requestBody = new MultipartBuilder()       .type(MultipartBuilder.FORM)       .addPart(           Headers.of("Content-Disposition", "form-data; name=\"title\""),           RequestBody.create(null, "Square Logo"))       .addPart(           Headers.of("Content-Disposition", "form-data; name=\"image\""),           RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))       .build();    Request request = new Request.Builder()       .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)       .url("https://api.imgur.com/3/image")       .post(requestBody)       .build();    Response response = client.newCall(request).execute();   if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string()); } 

You'll need to adapt this to S3, but the classes you need should be the same.

like image 167
Jesse Wilson Avatar answered Sep 22 '22 18:09

Jesse Wilson