Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Form data in retrofit2 android

Hi i have a json to send to the server (POST METHORD){"country":"india","devicetype":"android"} it is in form data model like the key for this json is data ie is the server accept it like

data={"country":"india","devicetype":"android"} am using retrofit i use Multipart like this

@Multipart
@POST("initiate")
@Headers({
        "Content-Type: application/json",
        "Cache-Control: no-cache"
})
Call<UserInfoServerResponse> getUserInfoRequest(@Part(value="data") UserInfo mUserInfo);

here UserInfo is the json but am getting fail message from server after that i used FormUrlEncoded methord

 @FormUrlEncoded
@POST("initiate")
@Headers({
        "Content-Type: application/json",
        "Cache-Control: no-cache"
})
Call<UserInfoServerResponse> getUserInfoRequest(@Field(value="data",encoded = false) String mUserInfo);

its out put is also same failure result from server, but the data sending to the server is in the formate

data=%7B%22country%22%3A%22india%22%2C%22devicetype%22%3A%22%22%7D

My UserInfo.class

public class UserInfo {


public String country;

public String devicetype;

public UserInfo( String country,String devicetype) {

    this.country=country;

    this.devicetype=devicetype;
}
}

My adaptor class

RemoteRetrofitInterfaces mService;
    Retrofit mRetrofit;
  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).addInterceptor(interceptor)
                .build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(AppConstant.HOST).addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        mService = mRetrofit.create(RemoteRetrofitInterfaces.class);

   Call<UserInfoServerResponse> api = mService.getUserInfoRequest(new Gson().toJson(mUserInfo));

        api.enqueue(new Callback<UserInfoServerResponse>() {
            @Override
            public void onResponse(Call<UserInfoServerResponse> responseCall, Response<UserInfoServerResponse> response) {

                if (response.body().status != null) {
                    if (response.body().status.equals("success")) {
                        Log.d(TAG, "success---");
                    }

                } else {
                    Log.d(TAG, "Failed---");

                }


            }

            @Override
            public void onFailure(Call<UserInfoServerResponse> responseCall, Throwable t) {
                t.printStackTrace();
            }


        });

so how can i send the json to server using retrofit successfully i gone through the retofit document and follow couple of steps but i dont get any result. can any one help me in this

Thank you

like image 943
Ramz Avatar asked Feb 29 '16 07:02

Ramz


People also ask

What is multipart form data in Android?

A multipart request is an HTTP request that HTTP clients create to send files and data to an HTTP server. A multipart message is made up of several parts. One part consists of a header and a body. The body can be any type of media and can contain text or binary data. A multipart media type can be included in a part.

How do I send a binary file in retrofit?

I use its solution : API Service: @POST("trip/{tripId}/media/photos") Call<MediaPost> postEventPhoto( @Path("eventId") int tripId, @Header("Authorization") String accessToken, @Query("direction") String direction, @Body RequestBody photo);

How do you send multipart form data in retrofit?

You can send a POST / PUT request by either submitting a body depending on the API Content Type Form Data, Form URL Encoded, or using JSON. To submit a JSON object you can use the @SerializedName to specify how to send each field data in the request.


2 Answers

finally i found the solution hope this will help some other

i achieve the solution by using FieldMap

of retrofit.

@POST("initiate")
@FormUrlEncoded

Call<UserInfoServerResponse> getUserInfoRequest(@FieldMap Map<String,String> params);

and in the Rest Adaptor section i changed request data from string to Hashmap form like following

Log.d(TAG, "sendUserInfo called");
UserInfo mInfo = new UserInfo("countyname","android");
String request = new Gson().toJson(mUserInfo);

// Here the json data is add to a hash map with key data
Map<String,String> params = new HashMap<String, String>();
params.put("data", request);


Call<UserInfoServerResponse> api = mService.getUserInfoRequest(params);

api.enqueue(new Callback<UserInfoServerResponse>() {
    @Override
    public void onResponse(Call<UserInfoServerResponse> responseCall, Response<UserInfoServerResponse> response) {

        if (response.body().status != null) {
            if (response.body().status.equals("success")) {
                Log.d(TAG, "success---" + response.body());
            }
        } else {
            Log.d(TAG, "Failed---");
        }

    }

    @Override
    public void onFailure(Call<UserInfoServerResponse> responseCall, Throwable t) {
        t.printStackTrace();
    }

});

Basilcally what I used @FormUrlEncoded for form data and @FieldMap to put my request JSON as a key value. i got solution by following this method, hope this will help some one :)

like image 113
Ramz Avatar answered Sep 29 '22 04:09

Ramz


The above solution works but is cumbersome to use , a better solution will be to use a converter for @Multipart formData

Please use the bellow code for proceeding with @Multipart FormData This is because

"" is added to your posting strings

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by kural on 10/27/17.
 */

public class StringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

public static StringConverterFactory create() {
        return new StringConverterFactory();
        }

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
        return new Converter<ResponseBody, String>() {

@Override
public String convert(ResponseBody value) throws IOException {
        return value.string();
        }
        };
        }
        return null;
        }

@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    if (String.class.equals(type)) {
        return new Converter<String, RequestBody>() {
            @Override
            public RequestBody convert(String value) throws IOException {
                return RequestBody.create(MEDIA_TYPE, value);
            }
        };
    }

    return null;

}
}

and in your retrofit client add this line

.addConverterFactory(StringConverterFactory.create())

public class RetroFitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

            /*retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();*/
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(client)
                    .addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();


        }
        return retrofit;
    }
like image 45
Mughil Avatar answered Sep 29 '22 05:09

Mughil