i want to upload image using okhttp but i am not able to find MultipartBuilder for Post Image.What can i use instead of this.
Here is my code
public static JSONObject uploadImage(File file) { try { final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); RequestBody req = new MultipartBuilder().setType(MultipartBody.FORM) .addFormDataPart("userid", "8457851245") .addFormDataPart( "userfile", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, file) ) .build(); Request request = new Request.Builder() .url("url") .post(req) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); Log.d("response", "uploadImage:" + response.body().string()); 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; }
Thanks in advance.
What is OkHttp? OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.
The process of downloading the file has four steps. Create the request using the URL. Execute the request and receive a response. Get the body of the response, or fail if it's null.
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.
You need to Use
new MultipartBody.Builder()
Instead of
new MultipartBuilder()
Its working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With