Retrofit 2 with Only Form-Data

Retrofit 2 with only form-data

In retrofit 2.0 to perform POST request like above, you should use RequestBody type for your parameter like this.

@Multipart
@POST("XXXX")
Call<PlanResponse> myPlans(@Part(Constants.ACTION_ID) RequestBody actionId, @Part(Constants.OFFER_CODE) RequestBody offerCode);

And here how to get requestBody from String.

String somevalue = "somevalue";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), somevalue);

Retrofit2 (Android) - How to send form-data along POST method

I managed to find a solution, which turned out to be a lot easier than I thought.

Just crate a class called AuthRequest like this:

public class AuthRequest {

private static final String TAG = "Auth";
private static final String EMAIL = "email";
private static final String PASSWORD = "pass";

//creates a json-format string
public static String createAuthJsonString(){

String info = "{\"auth\":{\"email\":\""+EMAIL+"\",\"password\":\""+PASSWORD+"\"}}";

Log.i(TAG,info);

return info;
}

}

Just add @FormUrlEncoded to @Post and put @Field key and value inside method call:

@FormUrlEncoded
@POST("ys")//endpoint
Call<YList> getY(@Field("info") String info);

// Connection url.
public static final YService serviceY = new Retrofit.Builder()
.baseUrl("http://example.com.br/api/x/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(YService.class);

Using getY() method:

    final YService yService = YService.serviceY;
//...
yService.getY(AuthRequest.createAuthJsonString()).enqueue(new
Callback<YList>() {

@Override
public void onResponse(Call<YList> call, Response<YList> response) {

if (response.isSuccessful()) {
//...

} else {

//...
}
}

@Override
public void onFailure(Call<YList> call, Throwable t) {

//...

}

});

}

Returned YList from json perfectly.

Retrofit Post Request With Form data

**Make interface like this add "MultipartBody.Part" in request and set your image path as post method and you can upload image using retrofit use this networkclient class to create retrofit instance **

public class NetworkClient {
private static final String BASE_URL = "";
private static Retrofit retrofit;
public static Retrofit getRetrofitClient(Context context) {
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

}

public interface UploadAPIs {
@Multipart
@POST("/upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);
}

private void uploadToServer(String filePath) {
Retrofit retrofit = NetworkClient.getRetrofitClient(this);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
//Create a file object using file path
File file = new File(filePath);
// Create a request body with file and image media type
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
// Create MultipartBody.Part using file request-body,file name and part name
MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
//Create request body with text description and text media type
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
//
Call call = uploadAPIs.uploadImage(part, description);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}

POST Multipart Form Data using Retrofit 2.0 including image

I am highlighting the solution in both 1.9 and 2.0 since it is useful for some

In 1.9, I think the better solution is to save the file to disk and use it as Typed file like:

RetroFit 1.9

(I don't know about your server-side implementation) have an API interface method similar to this

@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
@Part("folder") String folder,
Callback<Response> callback);

And use it like

TypedFile file = new TypedFile("multipart/form-data",
new File(path));

For RetroFit 2 Use the following method

RetroFit 2.0 ( This was a workaround for an issue in RetroFit 2 which is fixed now, for the correct method refer jimmy0251's answer)

API Interface:

public interface ApiInterface {

@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser(@Header("Authorization") String authorization,
@Part("file\"; filename=\"pp.png\" ") RequestBody file,
@Part("FirstName") RequestBody fname,
@Part("Id") RequestBody id);
}

Use it like:

File file = new File(imageUri.getPath());

RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
file);

RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
firstNameField.getText()
.toString());

RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
AZUtils.getUserId(this));

Call<User> call = client.editUser(AZUtils.getToken(this),
fbody,
name,
id);

call.enqueue(new Callback<User>() {

@Override
public void onResponse(retrofit.Response<User> response,
Retrofit retrofit) {

AZUtils.printObject(response.body());
}

@Override
public void onFailure(Throwable t) {

t.printStackTrace();
}
});

How to send form-data parameter using Retrofit in Android

Why don't you use Multipart?
This is an example of using it for a simple user info with phone number, password and a prfile pic:

In your Activity:

final RequestBody rPhoneNumber = RequestBody.create(MediaType.parse("text/plain"), "sample phone number");
final RequestBody rPassword = RequestBody.create(MediaType.parse("text/plain"), "sample phone password");
final MultipartBody.Part rProfilePicture = null;
Retrofit.Builder builder = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(baseUrl).client(Cookie.cookie.build());
Retrofit retrofit = builder.build();
final RequestHandler requestHandler = retrofit.create(RequestHandler.class);
rProfilePicture = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"),file)); //sample image file that you want to upload
Call<ServerMessage> call; //ServerMessage is a class with a String to store and convert json response
call = requestHandler.editProfile(rPhoneNumber, rPassword, rProfilePicture); //editProfile is in RequestHandler interface
call.enqueue(new Callback<ServerMessage>() {
@Override
public void onResponse (Call < ServerMessage > call2, Response < ServerMessage > response){
//your code here
}

@Override
public void onFailure (Call < ServerMessage > call, Throwable t) {
//your code here
}
});

In RequestHandler.java interface:

    @Multipart
@POST("/api/change-profile")
Call<ServerMessage> editProfile(@Part("phoneNumber") RequestBody rPhoneNumber,
@Part("oldPassword") RequestBody rPassword,
@Part MultipartBody.Part rProfilePicture);

In ServerMessage.java:

public class ServerMessage {
private String message;

public String getMessage() {
return message;
}
}

How to send only form data in retrofit2 android.

In your retrofit interface:

@FormUrlEncoded
@POST("yourPath")
Call<YourResponseClass> callApi(@Field("category") int category_value);


Related Topics



Leave a reply



Submit