Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload using okHttp

Tags:

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.

like image 957
Dhaval Avatar asked Feb 25 '16 09:02

Dhaval


People also ask

What is OkHttp used for?

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.

How do I download from OkHttp?

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.

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.


1 Answers

You need to Use

new MultipartBody.Builder() 

Instead of

new MultipartBuilder() 

Its working

like image 56
RushDroid Avatar answered Sep 23 '22 03:09

RushDroid