how to use okhttp to upload a file? - java

I use okhttp to be my httpclient. I think it's a good api but the doc is not so detailed.
how to use it to make a http post request with file uploading?
public Multipart createMultiPart(File file){
Part part = (Part) new Part.Builder().contentType("").body(new File("1.png")).build();
//how to set part name?
Multipart m = new Multipart.Builder().addPart(part).build();
return m;
}
public String postWithFiles(String url,Multipart m) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
m.writeBodyTo(out)
;
Request.Body body = Request.Body.create(MediaType.parse("application/x-www-form-urlencoded"),
out.toByteArray());
Request req = new Request.Builder().url(url).post(body).build();
return client.newCall(req).execute().body().string();
}
my question is:
how to set part name? in the form, the file should be named file1.
how to add other fields in the form?

Here is a basic function that uses okhttp to upload a file and some arbitrary field (it literally simulates a regular HTML form submission)
Change the mime type to match your file (here I am assuming .csv) or make it a parameter to the function if you are going to upload different file types
public static Boolean uploadFile(String serverURL, File file) {
try {
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/csv"), file))
.addFormDataPart("some-field", "some-value")
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
// Handle the error
}
// Upload successful
}
});
return true;
} catch (Exception ex) {
// Handle the error
}
return false;
}
Note: because it is async call, the boolean return type does not indicate successful upload but only that the request was submitted to okhttp queue.

Here's an answer that works with OkHttp 3.2.0:
public void upload(String url, File file) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/plain"), file))
.addFormDataPart("other_field", "other_field_value")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();
}

Note: this answer is for okhttp 1.x/2.x. For 3.x, see this other answer.
The class Multipart from mimecraft encapsulates the whole HTTP body and can handle regular fields like so:
Multipart m = new Multipart.Builder()
.type(Multipart.Type.FORM)
.addPart(new Part.Builder()
.body("value")
.contentDisposition("form-data; name=\"non_file_field\"")
.build())
.addPart(new Part.Builder()
.contentType("text/csv")
.body(aFile)
.contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"")
.build())
.build();
Take a look at examples of multipart/form-data encoding to get a sense of how you need to construct the parts.
Once you have a Multipart object, all that's left to do is specify the right Content-Type header and pass on the body bytes to the request.
Since you seem to be working with the v2.0 of the OkHttp API, which I don't have experience with, this is just guess code:
// You'll probably need to change the MediaType to use the Content-Type
// from the multipart object
Request.Body body = Request.Body.create(
MediaType.parse(m.getHeaders().get("Content-Type")),
out.toByteArray());
For OkHttp 1.5.4, here is a stripped down code I'm using which is adapted from a sample snippet:
OkHttpClient client = new OkHttpClient();
OutputStream out = null;
try {
URL url = new URL("http://www.example.com");
HttpURLConnection connection = client.open(url);
for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
connection.setRequestMethod("POST");
// Write the request.
out = connection.getOutputStream();
multipart.writeBodyTo(out);
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
} finally {
// Clean up.
try {
if (out != null) out.close();
} catch (Exception e) {
}
}

I've created cool helper class for OkHttp3. it here
public class OkHttp3Helper {
public static final String TAG;
private static final okhttp3.OkHttpClient client;
static {
TAG = OkHttp3Helper.class.getSimpleName();
client = new okhttp3.OkHttpClient.Builder()
.readTimeout(7, TimeUnit.MINUTES)
.writeTimeout(7, TimeUnit.MINUTES)
.build();
}
private Context context;
public OkHttp3Helper(Context context) {
this.context = context;
}
/**
* <strong>Uses:</strong><br/>
* <p>
* {#code
* ArrayMap<String, String> formField = new ArrayMap<>();}
* <br/>
* {#code formField.put("key1", "value1");}<br/>
* {#code formField.put("key2", "value2");}<br/>
* {#code formField.put("key3", "value3");}<br/>
* <br/>
* {#code String response = helper.postToServer("http://www.example.com/", formField);}<br/>
* </p>
*
* #param url String
* #param formField android.support.v4.util.ArrayMap
* #return response from server in String format
* #throws Exception
*/
#NonNull
public String postToServer(#NonNull String url, #Nullable ArrayMap<String, String> formField)
throws Exception {
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder().url(url);
if (formField != null) {
okhttp3.FormBody.Builder formBodyBuilder = new okhttp3.FormBody.Builder();
for (Map.Entry<String, String> entry : formField.entrySet()) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
requestBuilder.post(formBodyBuilder.build());
}
okhttp3.Request request = requestBuilder.build();
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException(response.message());
}
return response.body().string();
}
/**
* <strong>Uses:</strong><br/>
* <p>
* {#code
* ArrayMap<String, String> formField = new ArrayMap<>();}
* <br/>
* {#code formField.put("key1", "value1");}<br/>
* {#code formField.put("key2", "value2");}<br/>
* {#code formField.put("key3", "value3");}<br/>
* <br/>
* {#code
* ArrayMap<String, File> filePart = new ArrayMap<>();}
* <br/>
* {#code filePart.put("key1", new File("pathname"));}<br/>
* {#code filePart.put("key2", new File("pathname"));}<br/>
* {#code filePart.put("key3", new File("pathname"));}<br/>
* <br/>
* {#code String response = helper.postToServer("http://www.example.com/", formField, filePart);}<br/>
* </p>
*
* #param url String
* #param formField android.support.v4.util.ArrayMap
* #param filePart android.support.v4.util.ArrayMap
* #return response from server in String format
* #throws Exception
*/
#NonNull
public String postMultiPartToServer(#NonNull String url,
#Nullable ArrayMap<String, String> formField,
#Nullable ArrayMap<String, File> filePart)
throws Exception {
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder().url(url);
if (formField != null || filePart != null) {
okhttp3.MultipartBody.Builder multipartBodyBuilder = new okhttp3.MultipartBody.Builder();
multipartBodyBuilder.setType(okhttp3.MultipartBody.FORM);
if (formField != null) {
for (Map.Entry<String, String> entry : formField.entrySet()) {
multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
if (filePart != null) {
for (Map.Entry<String, File> entry : filePart.entrySet()) {
File file = entry.getValue();
multipartBodyBuilder.addFormDataPart(
entry.getKey(),
file.getName(),
okhttp3.RequestBody.create(getMediaType(file.toURI()), file)
);
}
}
requestBuilder.post(multipartBodyBuilder.build());
}
okhttp3.Request request = requestBuilder.build();
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException(response.message());
}
return response.body().string();
}
private okhttp3.MediaType getMediaType(URI uri1) {
Uri uri = Uri.parse(uri1.toString());
String mimeType;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return okhttp3.MediaType.parse(mimeType);
}
}

OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("File", path.getName(),RequestBody.create(MediaType.parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),path))
.addFormDataPart("username", username)
.addFormDataPart("password", password)
.build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
result = response.body().string();
Above code will send the username, password as the post parameter and the file will be uploaded in the name of "File".
PHP Server will receive the files
if (isset($_FILES["File"]) &&
isset($_POST['username']) &&
isset($_POST['password'])) {
//All Values found
}else{
echo 'please send the required data';
}

Perfect code for uploading any files to google drive along with metadata of files easily.
String url = String.format("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart");
//String url = String.format("https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable");
boolean status;
String metaDataFile = "{\"title\":\"" + step.getFile_name() + "\"," +
"\"description\":\"" + step.getDescription() + "\"," +
"\"parents\":[{\"id\":\"" + step.getFolderId() + "\"}]," +
"\"capabilities\":{\"canEdit\":\"" + false + "\", \"canDownload\":\" "+ false +" \" }, " +
"\"type\":\"" + step.getFile_access() + "\"" +
"}";
//get the encoded byte data for decode
byte[] file = Base64.decodeBase64(step.getFile_data());
//attaching metadata to our request object
RequestBody requestBodyMetaData = RequestBody.create(MediaType.parse("application/json"), metaDataFile);
//passing both meta data and file content for uploading
RequestBody requestBodyMultipart = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("metadata", null, requestBodyMetaData)
.addFormDataPart("file", null, RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", String.format("Bearer %s", step.getAccess_token()))
.post(requestBodyMultipart)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
try {
// Get response after rest call.
Response response = okHttpClient.newCall(request).execute();
status = response.code() == 200 ? true : false;
map.put(step.getOutput_variable(), response.code());

Asynchronously ...
public void UploadFileFromOkhttp(String filePath, String jwtToken){
String url = "https://api.baserow.io/api/user-files/upload-file/";
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
File file = new File(filePath);
builder.addFormDataPart("file" , file.getName() , RequestBody.create(MediaType.parse("image/*"), file));
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "JWT "+ jwtToken)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
OnError(e.getMessage());
}
});
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String responseData = response.body().string();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
OnSuccess(responseData);
}
});
}
});
}

Related

Go from OkHttp to HttpURLConnection

For reasons of library compatibility issues I would like to use HttpURLConnection to call requests on an API.
Here is the code I use with OkHttp to get a token access:
private void getAccessToken(){
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder().add("grant_type", "authorization_code")
.add("client_id", "1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com")
.add("client_secret", "AMe0xxxxxxxxxxxx")
.add("redirect_uri", "")
.add("code", serverCode)
.build();
Request request = new Request.Builder()
.url("https://www.googleapis.com/oauth2/v4/token")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.i("severcode","failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
token = jsonObject.optString("access_token");
tokenExpired = SystemClock.elapsedRealtime() + jsonObject.optLong("expires_in") * 1000;
Log.i("severcode",String.valueOf(token));
createGooglePhotosClient();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
So I would like to know how to get the equivalent of requestbody to pass it in setRequestProperty ()?
Thanks for your help
The request body is not a request property (header), it's the body of the request, and without OkHttp or other supporting libraries you have to format it yourself, encode any special characters that need to be encoded etc.
String requestBody = "grant_type=authorization_code&client_id=1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com&"
+ "client_secret=AMe0xxxxxxxxxxxx&redirect_uri=&code=" + serverCode + "\n\n";
byte[] requestBodyBytes = requestBody.getBytes("UTF-8");
Once you have the request body, you write it to the connection's output stream. For example:
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
out = connection.getOutputStream();
out.write(requestBodyBytes)
out.flush();

Http Ok3 Returns two responses

I am connecting black box backend, I have no control over the source and cannot modify the backend, using Ok Http 3. But for some reason, I am getting two results and I don't know what's going on. I suspect two threads are becoming active. But I don't know how to stop it. I tried both Synchronous and Asynchronous connection to no effect. I am new to Ok Http 3, so I am not sure what I am doing wrong.
I/Results: {"TotalResultsCount":3,"Results":[{
I/Results: {"TotalResultsCount":24,"Results":[
Here's is my synchronous code
class CallBackendSync extends AsyncTask {
OkHttpClient client = new OkHttpClient();
JSONObject resultsObject = null;
#Override
protected Object doInBackground(Object [] objects) {
String searchTerm = (String) objects[0];
String url = (String) objects[1];
String token = (String) objects[2];
String results = "";
//Search Body
RequestBody searchBody = new FormBody.Builder()
.add("QueryText", searchTerm)
.add("Categories", "")
.add("ChargeOutPerMinuteFrom", "0")
.add("ChargeOutPerMinuteTo", "0")
.add("maxDistance", "0")
.add("longitude", "0")
.add("latitude", "0")
.add("page", "0")
.build();
//Create request
Request.Builder builder = new Request.Builder();
builder.url(url);
builder.addHeader("Accept", "application/json");
if (token != null) {
builder.addHeader("Authorization", token);
}
builder.post(searchBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
results = results + response.body().string();
resultsObject = new JSONObject(results);
Log.i("Results", results);
return resultsObject;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String s){
super.onPostExecute(s);
displayResults(resultsObject);
}
}
I am calling the backend from MainActivity using the code fragment below
CallBackendSync sync = new CallBackendSync();
String [] params = {searchTerm, serverBaseUrl + url, accessToken};
sync.execute(params);
Any ideas about what's going wrong will be much appreciated.

How to correctly upload a video to server using okhttp client?

I am trying to upload a video to a server using okhttp client and although the onsuccess method is reached the video is not playable on the website.
My question is, am I uploading the video correctly using the storage path or am I missing something?
public void videoUploadTo(String url, String storageUrl) {
OkHttpClient client = new OkHttpClient();
File videoFile = new File(storageUrl);
Uri videoUri = Uri.fromFile(videoFile);
String content_type = getMimeType(videoFile.getPath());
RequestBody fileBody = RequestBody.create(MediaType.parse(content_type), videoFile);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", content_type)
.addFormDataPart("uploaded_video", storageUrl.substring(storageUrl.lastIndexOf("/") + 1), fileBody)
.build();
Request request = new Request.Builder()
.url(siteUrl + url)
.put(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("onfailure video", e.getMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("onResponse video", response.message());
}
});
}
You can do something like this to create a Requestbody out of a FileInputStream:
final InputStream inputStream = new FileInputStream(videoFile);
final long fileSize;
fileSize = videoFile.length();
RequestBody requestBody = new RequestBody() {
#Override
public MediaType contentType() {
return MediaType.parse("video");
}
#Override
public long contentLength() throws IOException {
return fileSize;
}
#Override
public void writeTo(BufferedSink sink) throws IOException {
byte [] buffer = new byte[65536];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
sink.write(buffer, 0, bytesRead);
}
}
};
And then you can add that body as a part to your MultipartBody like this:
.addFormDataPart("video_file", videoFile.getName(), requestBody);

Android Google CloudPrint Submit a PDF print job via URL API

Im having trouble getting the correct code to send submit a multipart form with a PDF included to google cloud print( the reason I'm not using the inbuilt intent in android is that you cant automatically select a printer it need to be done manually when using the intent)
I have been using Volley to submit it but I have been reading its not great with large files?
final RequestQueue queue = Volley1.getInstance(this).getRequestQueue();
String url3 = "https://www.google.com/cloudprint/submit";
final VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url3 ,new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
Log.d("responseis",resultResponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("redirect_uri", "xxxxx");
params.put("printerid","xxxxxx");
params.put("title", "result1.pdf");
params.put("contentType", "application/pdf");
params.put("ticket", "{\"print\":{},\"version\":\"1.0\"}");
params.put("hl", "en");
return params;
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Authorization", "OAuth"+" "+res);
headers.put("Content-Type", "multipart/form-data; boundary=__1466595844361__");
//headers.put("Content-Type","application/x-www-form-urlencoded");
//Logger.debugE(Constants.accesstoken, headers.toString());
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
//String yourFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/PDFs/result1.pdf";
String yourFilePath=Environment.getExternalStorageDirectory().getAbsolutePath()+ "/PDFs/result1.pdf";
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "PDF_reader");
File text = new File(dir + File.separator + "test_r.pdf");
String input = text.getAbsolutePath();
byte[] data = new byte[(int) input.length()];
try {
//convert file into array of bytes
data = FileUtils.readFileToByteArray(text);
}catch(Exception e){
e.printStackTrace();
}
params.put("content", new DataPart("result1.pdf",data , "application/pdf"));
return params;
}
};
queue.add(multipartrequest);
After a lot of trial and error I ended up using OKHTTP library and I was successfully able to submit a print job to google cloud print using the API. It was a bit tricky to get the multipart form with the pdf file included but the correct working request is below. Obviously the token and printerid are retrieved in other requests and need to be added manually.
public void run() throws Exception {
//File directory
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "PDFs/result1.pdf");
if(file.canRead()){
Log.d("file", "can read");
}else {Log.d("file","cant read");};
// Final request body
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("content","result1.pdf",RequestBody.create(MediaType.parse("application/pdf"), file))
.build();
//URL Parameters
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegments("cloudprint/submit")
.addQueryParameter("printerid", "82d70sde-694b-3385-f263-164cb04320c3")
.build();
Request request = new Request.Builder()
.header("Authorization", "OAuth ya29.Cl0jAxDuQni_Dskz6Y2r-wRaJVMxEw8fy5hPNfAm02pDLnZc9HX-RfHpmMoS0OL-Wv_SKxBtYIwRK9jVpJDwl7Qs-RFt02Qc5Yoid4w1kV8b4vBIpcleIQ8lBEto")
.url(url)
.post(requestBody)
.build();
client.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(final Call call, IOException e) {
// Error
runOnUiThread(new Runnable() {
#Override
public void run() {
// For the example, you can show an error dialog or a toast
// on the main UI thread
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
String res = response.body().string();
// Do something with the response
}
});
}

Android okHttp addFormDataPart dynamically for Multiple Image

I had given answer Uploading a large file in multipart using OkHttp but i am stuck with multiple image uploading.
I want to upload dynamically 1 to 10 image at a time.
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart(KEY_PHOTO_CAPTION, photoCaption)
.addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
.build();
I have ArrayList of PhotoCaption class which has captionPhoto and urlPhoto so how can i addFormDataPart()
I am thinking to make loop and call this function that many times of ArrayList size.
Is there any solution to addFormDataPart() use dynamically?
Here I have created Function to Upload Multiple Images.
/**
* Here I am uploading MultipleImages from List of photoCaption
* Sending photoCaption with URL and Caption of Photo...
*
* #param albumId
* #param photoCaptions
* #return
*/
public static JSONObject uploadAlbumImage(String albumId, ArrayList<PhotoCaption> photoCaptions) {
try {
MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
int length = photoCaptions.size();
int noOfImageToSend = 0;
for(int i = 0; i < length; i++) {
/**
* Getting Photo Caption and URL
*/
PhotoCaption photoCaptionObj = photoCaptions.get(i);
String photoUrl = photoCaptionObj.getPhotoUrl();
String photoCaption = photoCaptionObj.getPhotoCaption();
File sourceFile = new File(photoUrl);
if(sourceFile.exists()) {
/** Changing Media Type whether JPEG or PNG **/
final MediaType MEDIA_TYPE = MediaType.parse(FileUtils.getExtension(photoUrl).endsWith("png") ? "image/png" : "image/jpeg");
/** Adding in MultipartBuilder **/
multipartBuilder.addFormDataPart(KEY_IMAGE_CAPTION + i, photoCaption);
multipartBuilder.addFormDataPart(KEY_IMAGE_NAME + i, sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile));
/** Counting No Of Images **/
noOfImageToSend++;
}
}
RequestBody requestBody = multipartBuilder
.addFormDataPart(KEY_ALBUM_ID, albumId)
.addFormDataPart(KEY_IMAGE_COUNT, String.valueOf(noOfImageToSend))
.build();
Request request = new Request.Builder()
.url(URL_ALBUM_UPLOAD_IMAGE)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
/** Your Response **/
String responseStr = response.body().string();
Log.i(TAG, "responseStr : "+ responseStr);
return new JSONObject(responseStr);
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}
I hope it will helps you.
This answer is for OkHttp2
For OkHttp3 You can see this post.
For multiple image you just need to run the loop as per your requirement, remaining part related to request will be same as you do.
// final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
final MediaType MEDIA_TYPE=MediaType.parse(AppConstant.arrImages.get(i).getMediaType());
//If you can have multiple file types, set it in ArrayList
MultipartBuilder buildernew = new MultipartBuilder().type(MultipartBuilder.FORM)
.addFormDataPart("title", title)
for (int i = 0; i < AppConstants.arrImages.size(); i++) {
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
TEMP_FILE_NAME + i + ".png");
if (f.exists()) {
buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f));
}
}
RequestBody requestBody = buildernew.build();
Request request = new Request.Builder()
.url(Url.URL + Url.INSERT_NEWS)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
return response.body().string();
Dont forget to delete temp. files that you uploaded if it is of no use.

Categories

Resources