27

I have used this method https://stackoverflow.com/a/31744565/5829906 but doesnt post data.

Here is my code

 OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {

            Response response = client.newCall(request).execute();
            String responseString = response.body().string();
            response.body().close();
        }catch (Exception e) {
            e.printStackTrace();
        }

I tried DefaultHttpClient , that seems to be working, but it shows deprecated, so thought of trying something different..Cant figure out what is wrong in this

Community
  • 1
  • 1
MrRobot9
  • 2,402
  • 4
  • 31
  • 68

2 Answers2

38

You select MediaType MultipartBuilder.FORM which is for uploading the file/image as multipart

public static final MediaType FORM = MediaType.parse("multipart/form-data");

try to send like this as

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception { 
    RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build(); 
    Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build(); 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response); 
    System.out.println(response.body().string()); 
}

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • 2
    For current version, replace FormBody with MultipartBody https://github.com/square/okhttp/wiki/Recipes –  May 23 '18 at 17:29
  • I have to pass Content-Type:application/x-www-form-urlencoded(header, and a token value ),, and with a form-body of some key value pair, But okhtp always giving me 401 unauthorized error, how to do that with okhttp? – B.shruti Jul 10 '18 at 06:41
  • 1
    401 means unauthorized you are sending invalid access token to the server thats why you are getting 401 – Moktahid Al Faisal Jul 10 '18 at 07:02
3

For those that may still come here, using with Retrofi2 and passing your data correctly to the request body. Even if you set "application/x-www-form-urlencoded" and you did not pass your data properly, you will still have issue. That was my situstion

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("ContentType", "application/x-www-form-urlencoded");
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl(URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);

Then make sure you pass your data to your api endpoint as shown below. NOT as JSON, or class object or string but as request body.

RequestBody formBody = new FormBody.Builder()
        .addEncoded("grant_type", "password")
        .addEncoded("username", username)
        .addEncoded("password", password)
        .build();

call your api service

Call<Response> call = api.login(formBody);

I hope this helps somebody

Damilinks
  • 349
  • 3
  • 9
  • Which dependency defines the "Api" variable type? Android studio recommends importing some com.google.gms..... class, but that doesn't seem to be the right one. – Josh Apr 28 '20 at 15:11
  • .addEncoded("key", value) did it for me. Using OkHTTP only – bastiotutuama Sep 04 '20 at 15:21