Upload a file using okhttp

I am completing this project that uses okhttp to communicate with webservice.

Everything works fine for regular GET and POST, but I can't load the file correctly.

The okhttp docs are sorely lacking on these topics, and everything I found here or somewhere doesn't seem to work in my case.

It should be simple: I have to send both the file and some string values. But I can’t figure out how to do this.

Following some patterns that I found, I tried this first:

RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("group", getGroup()) .addFormDataPart("type", getType()) .addFormDataPart("entity", Integer.toString(getEntity())) .addFormDataPart("reference", Integer.toString(getReference())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile())) .build(); 

This gives me the error "400 bad request."

So, I tried this from okhttp recipes:

 RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addPart(Headers.of("Content-Disposition", "form-data; name=\"group\""), RequestBody.create(null, getGroup())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"type\""), RequestBody.create(null, getType())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"entity\""), RequestBody.create(null, Integer.toString(getEntity()))) .addPart(Headers.of("Content-Disposition", "form-data; name=\"reference\""), RequestBody.create(null, Integer.toString(getReference()))) .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile())) .build(); 

The same result.

I don’t know what else to try or what to think in order to debug this.

The request is executed using this code:

 // adds the required authentication token Request request = new Request.Builder().url(getURL()).addHeader("X-Auth-Token", getUser().getToken().toString()).post(requestBody).build(); Response response = client.newCall(request).execute(); 

But I'm sure the problem is how Im creates the request body.

What am I doing wrong?

EDIT: "getFile ()" above returns a File object, by the way. The remaining parameters are all strings and ints.

+8
java android
May 20 '15 at 2:28
source share
4 answers

I found the answer to my question a little after the first post.

I will leave it here because it may be useful to others, given that there are several examples of loading okhttp:

 RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("group", getGroup()) .addFormDataPart("type", getType()) .addFormDataPart("entity", Integer.toString(getEntity())) .addFormDataPart("reference", Integer.toString(getReference())) .addFormDataPart("task_file", "file.png", RequestBody.create(MediaType.parse("image/png"), getFile())) .build(); 

There is no reason to use addPart with Headers.of, etc., as in recipes, addFormDataPart does the trick.

And for the file field itself, it takes 3 arguments: name, file name, and then the body of the file. What is it.

+20
May 20 '15 at 12:38
source

I just changed addFormDataPart instead of addPart and finally solved my problem using the following code:

  /** * Upload Image * * @param memberId * @param sourceImageFile * @return */ public static JSONObject uploadImage(String memberId, String sourceImageFile) { try { File sourceFile = new File(sourceImageFile); Log.d(TAG, "File...::::" + sourceFile + " : " + sourceFile.exists()); final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart("member_id", memberId) .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) .build(); Request request = new Request.Builder() .url(URL_UPLOAD_IMAGE) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); return new JSONObject(response.body().string()); } catch (UnknownHostException | UnsupportedEncodingException e) { Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; } 
+6
Dec 02 '15 at 7:26
source

in OKHTTP 3+ use this AsyncTask

SignupWithImageTask

  public class SignupWithImageTask extends AsyncTask<String, Integer, String> { ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(SignupActivity.this); progressDialog.setMessage("Please Wait...."); progressDialog.show(); } @Override protected String doInBackground(String... str) { String res = null; try { // String ImagePath = str[0]; String name = str[0], email = str[1], dob = str[2], IMEI = str[3], phone = str[4], ImagePath = str[5]; File sourceFile = new File(ImagePath); Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists()); final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*"); String filename = ImagePath.substring(ImagePath.lastIndexOf("/") + 1); /** * OKHTTP2 */ // RequestBody requestBody = new MultipartBuilder() // .type(MultipartBuilder.FORM) // .addFormDataPart("member_id", memberId) // .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) // .build(); /** * OKHTTP3 */ RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("image", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) .addFormDataPart("result", "my_image") .addFormDataPart("name", name) .addFormDataPart("email", email) .addFormDataPart("dob", dob) .addFormDataPart("IMEI", IMEI) .addFormDataPart("phone", phone) .build(); Request request = new Request.Builder() .url(BASE_URL + "signup") .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); okhttp3.Response response = client.newCall(request).execute(); res = response.body().string(); Log.e("TAG", "Response : " + res); return res; } catch (UnknownHostException | UnsupportedEncodingException e) { Log.e("TAG", "Error: " + e.getLocalizedMessage()); } catch (Exception e) { Log.e("TAG", "Other Error: " + e.getLocalizedMessage()); } return res; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); if (progressDialog != null) progressDialog.dismiss(); if (response != null) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("message").equals("success")) { JSONObject jsonObject1 = jsonObject.getJSONObject("data"); SharedPreferences settings = getSharedPreferences("preference", 0); // 0 - for private mode SharedPreferences.Editor editor = settings.edit(); editor.putString("name", jsonObject1.getString("name")); editor.putString("userid", jsonObject1.getString("id")); editor.putBoolean("hasLoggedIn", true); editor.apply(); new UploadContactTask().execute(); startActivity(new Intent(SignupActivity.this, MainActivity.class)); } else { Toast.makeText(SignupActivity.this, "" + jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } else { Toast.makeText(SignupActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show(); } } } 
+2
Nov 29 '16 at 13:06
source

I also encounter a problem when uploading a file to my web server. Below is the code I'm trying with. This may sound silly, but I tried for many days to no avail. Would appreciate if anyone can help me here. I get an error where I execute Response responseF = ClientF.newCall (requestF) .execute ();

 try { Log.d("pk", "KA 1 " + pictureFile.getPath()); final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); OkHttpClient ClientF = new OkHttpClient(); RequestBody BodyF=new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file","profile.png",RequestBody.create(MEDIA_TYPE_PNG,pictureFile.getPath())) .build(); Log.d("PK","Request Body generated"); Request requestF=new Request.Builder() .url(url) .post(BodyF) .build(); Log.d("PK","Entering in try"); try { Response responseF= ClientF.newCall(requestF).execute(); Log.d("PK","request successful" + responseF.body().string()); } catch (IOException exx) { Log.d("PK","Catcher exx " + exx.getLocalizedMessage()); } } catch (Exception ex) { Log.d ("PK", "get message " + ex.getMessage()); } 
0
Jun 30 '19 at 7:45
source



All Articles