Enqueue callback is not calling for multipart - android

I am using multipart to upload a file to retrofit but enqueue is not calling
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("1", "bilal", part,"03232", "abnslfjns", true);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, retrofit2.Response response) {
Log.d("MainActivity", "onResponse: " + response);
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "onResponse: " + t);
}
});
}

Related

Retrofit multipart array key but single value only

My target or my goal is to have a request like this so that it will succeed:
Now my current code looks like this:
WebApi client = ServiceGenerator.createService(WebApi.class);
final Call<BaseResponse<BookingInfoEntity>> call = client.startBooking(
WebUtilities.createPartFromString(SharePreferences.getUserId(context)),
WebUtilities.createPartFromString(""), //trainer_id
WebUtilities.createPartFromString(String.valueOf(listener.getTrainerTypesObject().get(0))), //train type
WebUtilities.createPartFromString(String.valueOf(hours)),
WebUtilities.createPartFromString(String.valueOf(payment_id)),
WebUtilities.createPartFromString(SharePreferences.getCityId(context)),
WebUtilities.createPartFromString(listener.getSelectedDate()));
}
public static RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(okhttp3.MultipartBody.FORM, descriptionString);
}
#Multipart
#POST(START_BOOKING)
Call<BaseResponse<BookingInfoEntity>> startBooking(#Part("trainee_id") RequestBody trainee_id,
#Part("trainer_id") RequestBody trainer_id,
#Part("trainer_types[][trainer_type_id]")RequestBody train_type,
#Part("number_of_hours") RequestBody number_of_hours,
#Part("payment_type_id") RequestBody payment_type_id,
#Part("city_id") RequestBody city_id,
#Part("meeting_date") RequestBody meeting_date);
My problem is: How can i dynamically insert
trainer_types[][trainer_type_id],
like i want when i have 5 trainer type id,
how can i insert a 5 trainer_type_id in they key and set a value with it?
I just want to replicate the image above so that i can properly solve this value.
Your request should be like this:
#Multipart
#POST(START_BOOKING)
Call<BaseResponse<BookingInfoEntity>> startBooking(#Part("trainee_id") RequestBody trainee_id,
#Part("trainer_id") RequestBody trainer_id,
#Part List<MultipartBody.Part> train_type,
#Part("number_of_hours") RequestBody number_of_hours,
#Part("payment_type_id") RequestBody payment_type_id,
#Part("city_id") RequestBody city_id,
#Part("meeting_date") RequestBody meeting_date);
Create List of trainer_types for file types
#NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri, String file_type) {
File file;
if (file_type.contains("video")) {
file = new File(fileUri.getPath());
} else {
file = FileUtils.getFile(this, fileUri);
}
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName().replaceAll(" ", "%20"), requestFile);
}
Call API with multiple Same keys dientional arrays
private void startUploadingList(ArrayList<String> selectedItems1) {
List<MultipartBody.Part> parts = new ArrayList<>();
try {
for (int i = 0; i < selectedItems1.size(); i++) {
if (selectedItems1.get(i) != null) {
parts.add(prepareFilePart("trainer_types[][" + i + "]", Uri.parse(selectedItems1.get(i)), "image/png"));
}
}
RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Value");
// add another part within the multipart request
// finally, execute the request
Call<BaseResponse<BookingInfoEntity>> call = APIClient.getInterface().startBooking(description ,description ,parts, description,description ,description ,description );
call.enqueue(new Callback<BaseResponse<BookingInfoEntity>>() {
#Override
public void onResponse(Call<BaseResponse<BookingInfoEntity>> call, Response<BaseResponse<BookingInfoEntity>> response) {
Log.e("Upload", "success");
}
#Override
public void onFailure(Call<BaseResponse<BookingInfoEntity>> call, Throwable t) {
call.cancel();
Log.e("Upload error:", t.getMessage());
t.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

Retrofit Post Request With Form data

I am new to android .
I want to upload image as form data using Retrofit Post method.
I am using com.squareup.retrofit2:retrofit:2.3.0
This is my request body.
**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) {
}
});
}
Try this
#Multipart
#POST(Global.updateProfilePicture)
Call<YOUR_RESPONSE_MODEL> updatePicture(#Header("Authorization") String authorization, #PartMap Map<String, RequestBody> params);
And API call should be like this
public void updatePic(String senderID, String receiverID, String type, File photo) {
mProgressDialog.show();
final Map<String, RequestBody> map = new HashMap<>();
try {
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), photo);
map.put("image\"; filename=\"" + photo.getName() + "\"", fileBody);
} catch (Exception e) {
e.printStackTrace();
}
map.put("sender_id", RequestBody.create(MediaType.parse("multipart/form-data"), senderID));
map.put("receiver_id", RequestBody.create(MediaType.parse("multipart/form-data"), receiverID));
map.put("type", RequestBody.create(MediaType.parse("multipart/form-data"), type));
Call<YOUR_RESPONSE_MODEL> call = mApiInterface.updatePicture(ACCESS_TOKEN, map);
call.enqueue(new Callback<YOUR_RESPONSE_MODEL>() {
#Override
public void onResponse(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Response<YOUR_RESPONSE_MODEL> response) {
if (mContext != null) {
mProgressDialog.dismiss();
// Dismiss Dialog
}
}
#Override
public void onFailure(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Throwable t) {
if (mContext != null) {
mProgressDialog.dismiss();
}
}
});
}
I got output by doing request as following
UploadAPI Interface
`
#Multipart
#Headers({"TOKEN:XXXX"})
#POST("/api/messages/image")Call<ImageResult>uploadImage(#Part("sender_id")RequestBody sender_id,#Part("receiver_id")RequestBody receiver_id,#Part("type")RequestBody type,#Part MultipartBody.Part image);`
And Following is Method Code, I tried
`
private void uploadToServer(String filePath)
{
Retrofit retrofit = NetworkClient.getRetrofitClient(this, sendImageMsgURL);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
File file = new File(filePath);
MultipartBody.Part requestImage = null;
RequestBody requestFile = RequestBody.create(MediaType.parse("mutlipart/form-
data"),file);
requestImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
RequestBody sender_id = RequestBody.create(MediaType.parse("multipart/form-data"),
currentID);
RequestBody receiver_id = RequestBody.create(MediaType.parse("multipart/form-data"),
otherID);
RequestBody type = RequestBody.create(MediaType.parse("multipart/form-data"), "image");
Call<ImageResult> call = uploadAPIs.uploadImage(sender_id, receiver_id, type,
requestImage);
call.enqueue(new Callback<ImageResult>()
{
private Call<ImageResult> call;
private Response<ImageResult> response;
#Override
public void onResponse(Call<ImageResult> call, Response<ImageResult> response)
{
this.call = call;
this.response = response;
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("Error--------- :", t.getMessage());
}
});
}`

Found error 'Response{protocol=http/1.1, code=404, message=Not Found, url=url}' when sending file through retrofit2

I am facing problem when sending file through retrofit2. But the web api working fine on Postman hit. Error Stated in responsebody:
Response{protocol=http/1.1, code=404, message=Not Found, url=MYURL}
Retrofit2 endpoint:
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
Updated code:
// Uploading File
private void uploadFile() {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "dbBackup"+
File.separator +"gps_db_4522_190122114644.sqlite");
//File file = new File(mediaPath);
Retrofit retrofit = RetrofitSingleton.getInstance(getActivity().getBaseContext());
final CommonApiInterface commonApiInterface = retrofit.create(CommonApiInterface.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
commonApiInterface.uploadFile(fileToUpload,filename).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()) {
Toast.makeText(getActivity(), "Saved Successfully...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "Save Fail: " + t, Toast.LENGTH_SHORT).show();
}
});
}
Finally i found my problem. The endpoint was incorrect
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
correct endpoint is #POST("FileProcessing/UploadDataFile")

Retrofit2 response on file upload

I want to upload zip file on myserver. I am using Retrofit2. I have used the following code.
private void uploadFile() {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
File file = uploadFile;
RequestBody requestFile =
RequestBody.create(
MediaType.parse("application/x-www-form-‌urlencoded"),
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileUpload", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
Call<JSONObject> call = service.upload(description, body);
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call,
Response<JSONObject> response) {
System.out.println("UploadFragment.onResponse " + response);
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d("Upload error:", t.getCause().toString());
}
});
}
My upload service is like.
public interface FileUploadService {
#Multipart
#POST("myurl")
Call<JSONObject> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Problem When I upload file I get response {protocol=http/1.1, code=200, message=OK, url=http://myUrl.
It is not the response returned by my server. How can get my server response?
Its retrofit response. You will get your response in body.
response.body().toString();
Use this
System.out.println("UploadFragment.onResponse " + response.body().toString());
I hope this will help you.

Android Studio: retrofit2: multipart connection failure with image and strings

private void Dialog_profile_pic() {
// create upload service client
File file = new File(selectedImagePath);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("memFile", file.getName(), requestFile);
// add another part within the multipart request
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), ApiResultCode.getApiKey());
RequestBody description2 =
RequestBody.create(
MediaType.parse("multipart/form-data"), ApiResultCode.getApiType());
Call<LoginPicture> loginPictureCall = RequestClient.getInstance()
.loginPicture(description, description2, body);
loginPictureCall.enqueue(new Callback<LoginPicture>() {
#Override
public void onResponse(Call<LoginPicture> call, Response<LoginPicture> response) {
//CONNECTION SUCCESS
LoginPicture NewUser = response.body();
if (NewUser.getResponsedata().getResultCode() == 100) {
Log.e("DEBUG", "CONNECTION result: CONGRATS");
} else {
Log.e("DEBUG", "CONNECTION result: " + NewUser.getResponsedata().getResultCode() + NewUser.getResponsedata().getResultMessage());
}
}
#Override
public void onFailure(Call<LoginPicture> call, Throwable t) {
//CONNECTION FAIL
Log.e("DEBUG", "CONNECTION result: FAIL" );
}
});
}
\
public interface ApiInterface {
#Multipart
#POST("/memberController/joinUploadProfile.json")
Call<LoginPicture> loginPicture(#Part("apiKey") RequestBody apiKey, #Part("apiType") RequestBody apiType, #Part("memFile") MultipartBody.Part file); //multi part
\
I am trying to pass in two string parameters and an image file using retrofit2 but I am failing to get a connection. Anyone can help me find what I need to do? I have been struggling over this for 2 days now.
//In Request Client API Interface
#Multipart
#POST("URL.json")
Call<LoginPicture> loginPicture(#PartMap() Map<String, RequestBody> mapPhoto); //multi part
//In activity
private void Dialog_profile_pic(final Uri selectedImageUri) {
// create upload service client
File file = new File(selectedImagePath);
HashMap<String, RequestBody> map = new HashMap<>();
RequestBody description =
RequestBody.create(
MediaType.parse("text/plain"),"content1");
RequestBody description2 =
RequestBody.create(
MediaType.parse("text/plain"), "content2");
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/jpeg"), file);
map.put("memFile\"; filename=\""+file.getName(),requestFile);
map.put("apiKey",description);
map.put("apiType", description2);
Call<LoginPicture> loginPictureCall = RequestClient.getInstance()
.loginPicture(map);
loginPictureCall.enqueue(new Callback<LoginPicture>() {
#Override
public void onResponse(Call<LoginPicture> call, Response<LoginPicture> response) {
Picasso.with(Activity_create.this).load(NewUser.getResponsedata().getResultObject()).into(iv_profile_pic);
} else {
Log.e("DEBUG", "CONNECTION result: " + NewUser.getResponsedata().getResultCode() + NewUser.getResponsedata().getResultMessage());
}
}
#Override
public void onFailure(Call<LoginPicture> call, Throwable t) {
//통신 실패 시
Log.e("DEBUG", "CONNECTION result: FAIL");
}
});
}
//And it works now

Categories

Resources