Showing posts with label okhttp. Show all posts
Showing posts with label okhttp. Show all posts

Friday, July 24, 2015

OKHTTP S3 FIle upload via Signed URL

Here is the sample code in java to upload a file to S3 via OK HTTP client. We will need two dependencies -


  1. okhttp-2.4.0.jar
  2. okio-1.4.0.jar
Other than this we will need this piece of code to upload the file - 



package okhttpfileupload;


import java.io.File;
import java.io.IOException;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class Upload {
final OkHttpClient client = new OkHttpClient();
final String ENDPOINT = "https://bucket.s3-region.amazonaws.com/filename.jpg?AWSAccessKeyId=ACCESSKEYHERE&Content-Type=image%2Fjpg&Expires=1437757726&Signature=SIGNATUREHERE&x-amz-acl=public-read";
String imagePath = "/home/devendra/Desktop/pokemon.jpg";
public static void main(String[] args) throws IOException {
new Upload().uploadFile();
}

private void uploadFile() throws IOException {
File file = new File(imagePath);

   Request request = new Request.Builder()
   .header("Content-Type", "image/jpg")
        .url(ENDPOINT)
       .put(RequestBody.create(MediaType.parse("image/jpg"), file))
       .build();
   System.out.println("Upload started.");
   Response response = client.newCall(request).execute();
   System.out.println("Request complete.");
   if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

   System.out.println(response.body().string());
}
}




All you have to do is change the imagePath and ENDPOINT.


Happy Coding!