How to make request from retrofit android if the request to server looks like in the image.
Well, you could search about this before posting, quite sure you could have found something already, but..
#Multipart
#POST(RestClient.UPDATE_USER_PICTURE)
Call<BooleanResponse> updateUserPicture(#Part MultipartBody.Part picture, #Part("picture") RequestBody file);
Above part is the retrofit interface method that you'll use
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), loadImageFile);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("picture", loadImageFile.getName(), reqFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), loadImageFile.getName());
RestClient.getApi().updateUserPicture(filePart, filename).enqueue(new Callback<BooleanResponse>() {
#Override
public void onResponse(Call<BooleanResponse> call, Response<BooleanResponse> response) {
if (response.isSuccessful() && response.code() == 200){
Toast.makeText(CompleteProfile.this, "Picture updated successfully!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<BooleanResponse> call, Throwable t) {
Toast.makeText(CompleteProfile.this, "Request failed !" + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.e(TAG, "-=onFailure=-\n" + t.getMessage(), t);
}
});
Related
I am trying to upload files from android device to the server using retrofit.
But every time, it results with no in the console.
FilesApi.java:
public interface FilesApi {
#Multipart
#POST("file")
Call<String> storeFile(#Part MultipartBody.Part file);
}
In MainActivity.java:
private void uploadFile(){
RequestBody requestFile= RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", file.getName(), requestFile);
//RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
FilesApi api = RetrofitService.createService(FilesApi.class);
api.storeFile(body).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d(TAG, "onResponse: "+response.body());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d(TAG, "onFailure: "+t);
}
});
}
PHP code:
<?php
if(isset($_FILES['file']))
{
echo "YESS";
}
else
{
echo "no";
}
?>
The Filename should be the same on the Retrofit Parameter as well on the Server Key.
Please refer this link for complete guidance.
https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
I am trying to upload a video file using multipart by retrofit and I get the following error in response
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=serverurl/Upload/Videos/}
This is my code for file upload
void uploadVideo(String videoPath) {
dialog.show();
File videoFile = new File(videoPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoPath);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("file", videoFile.getName(), requestFile);
apiCall.uploadVideoToServer(presenter.getUserInfo().getUploadVideoPath(), vFile).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
}
});
}
This is the path I am uploading the file to
http://serverurl.com/Upload/Videos/
Can someone tell me whats wrong with my code?
Retrofir API interface
#Multipart
#POST
Call<String> uploadVideoToServer(#Url String url, #Part MultipartBody.Part video);
in your api service interface :
#Multipart
#POST("Upload/Videos") // *** DONT FORGET UR END POINT HERE ***
Call<urmodel> uploadVideoToServer(#PartMap Map<String, RequestBody> map);
and write a method to upload ur video file like this :
private void uploadVideoToServer(String path) {
File videoFile = new File(path);
if (videoFile.exists()) {
//create request body
Map<String, RequestBody> map = new HashMap<>();
RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
map.put("video\"; filename=\"" + videoFile.getName() + "\"", requestBody);
//make call
Call<urmodel> call = mTService.uploadVideoToServer(map);
call.enqueue(new Callback<urmodel>() {
#Override
public void onResponse(Call<urmodel> call, Response<urmodel> response) {
if (response.isSuccess()) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
#Override
public void onFailure(Call<urmodel> call, Throwable t) {
//occur when fail to deserialize || no network connection || server unavailable
Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
}
}
private void saveImageToServer(final String savedpath) {
showLoader();
NetworkUtil.checkInternetConnection(DetailActiveSRActivity.this, new NetworkUtil.NetworkStatusListener() {
#Override
public void onNetworkAvailable() {
File file = new File(savedpath);
// RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), savedpath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
Log.e(TAG, "onNetworkAvailable: requestFIle " + savedpath+"\n"+" file "+file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Log.e(TAG, "onNetworkAvailable: body " + body);
RequestBody reqUserId = RequestBody.create(MediaType.parse("text/plain"), userId);
//RequestBody reqImageType =RequestBody.create(MediaType.parse("text/plain"), "1");
Call<SaveImageResponseModel> responseCall = mService.saveImages(body, reqUserId);
responseCall.enqueue(new Callback<SaveImageResponseModel>() {
#Override
public void onResponse(Call<SaveImageResponseModel> call, retrofit2.Response<SaveImageResponseModel> response) {
hideLoader();
if (response != null) {
SaveImageResponseModel apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatus()) {
Log.e(TAG, "onRequestSuccess: " + apiResponse);
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<SaveImageResponseModel> call, Throwable t) {
hideLoader();
}
});
}
#Override
public void onNetworkNotAvailable() {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noNetworkMessage), Toast.LENGTH_SHORT).show();
hideLoader();
}
});
}
#Headers({
"authkey: ABCD#123"
})
#Multipart
#POST(UrlUtils.POST_IMAGES)
Call<SaveImageResponseModel> saveImages(#Part MultipartBody.Part file, #Part("userId") RequestBody userId);
First of all, no description, please add a little bit more.
Second:
show what is the content of mService.saveImages(body, reqUserId);
is the HTTP call of POST type?
is the endpoint really working? You should for example try to make call through Postman and you'll see, if it is going through
Hello guys here is my sample code
#FormUrlEncoded
#Multipart
#POST("registration.php")
Call<Signup> getSignupResponse(#Field("email") String email,
#Field("lname") String lname,
#Field("fname") String fname,
#Field("password") String password,
#Part("filename") File file);
Issue is when i am trying to add File Parameter as a Part its throwing me a error other wise if i use only #Field it works great but not working after i add #Part in it
- is there a no way to use #Field and #part together in Retrofit??
- If yes than tell a reason, If no tell me a proper way
I will appreciate your answer and thank you in advance
Note : Tell me a suggestions in comments before you vote.
You cannot use both #FormUrlEncoded and #Multipart on a single method.
An HTTP request can only have one Content-Type and both of those are
content types.
#FormUrlEncoded (for android) | application/x-www-form-urlencoded(for web)
#Multipart (for android) | multipart/form-data(for web)
use like this .....
#Multipart
#POST("photos/upload")
Call<Result> upload(#Part("Token") RequestBody token, #Part("Photo_Type") RequestBody type, #Part MultipartBody.Part file );
and in call like this .....
String token="your string";
File file = new File(path);
RequestBody tokenRequest = RequestBody.create(MediaType.parse("text/plain"), token);
RequestBody type = RequestBody.create(MediaType.parse("text/plain"), true + "");
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<Result> call = qikGrubApi.upload(tokenRequest, type, filePart);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
progress.dismiss();
if (response.isSuccessful()) {
if (response.body().getSuccess()) {
nextPage(response.body().getMessage());
} else
Toast.makeText(UploadActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UploadActivity.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progress.dismiss();
Toast.makeText(UploadActivity.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
Note:- Use above example for your File POST and let me know , if you stuck anywhere.
For more Detail info click this
EDIT:-
For your case use like this .....
#Multipart
#POST("registration.php")
Call<Signup> getSignupResponse(#Part("email") RequestBody email,
#Part("lname") RequestBody lname,
#Part("fname") RequestBody fname,
#Part("password") RequestBody password,
#Part MultipartBody.Part filename);
and use retrofit call like this .....
File file = new File(path);
RequestBody emailRequest = RequestBody.create(MediaType.parse("text/plain"), email);
RequestBody lnameRequest = RequestBody.create(MediaType.parse("text/plain"), lname);
RequestBody fnameRequest = RequestBody.create(MediaType.parse("text/plain"), fname);
RequestBody passwordRequest = RequestBody.create(MediaType.parse("text/plain"), password);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<Signup> call = qikGrubApi.upload(emailRequest, lnameRequest ,fnameRequest , passwordRequest, filePart);
call.enqueue(new Callback<Signup>() {
#Override
public void onResponse(Call<Signup> call, Response<Signup> response) {
progress.dismiss();
if (response.isSuccessful()) {
if (response.body().getSuccess()) {
nextPage(response.body().getMessage());
} else
Toast.makeText(UploadActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UploadActivity.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Signup> call, Throwable t) {
progress.dismiss();
Toast.makeText(UploadActivity.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
});
}
Example
I have android app that posts image to NodeJS server using Retrofit2.
Here is my Android/Java code:
public interface ApiInterface {
String ENDPOINT = "http://192.168.0.11:1337/";
#Multipart
#POST("users/avatar")
Call<Avatar> postAvatar(#Part("description") RequestBody description, #Part("image") MultipartBody.Part file);
public static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private void uploadAvatar(final String userid){
File file = new File("/storage/emulated/0/Android/data/com.bcg.loginexample/files/pic.jpg");
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
ApiInterface mApiService = ApiInterface.retrofit.create(ApiInterface.class);
Call<Avatar> mService= mApiService.postAvatar(description, body );
mService.enqueue(new Callback<Avatar>() {
#Override
public void onResponse(Call<Avatar> call, Response<Avatar> response) {
Avatar avatar = response.body();
String returnedResponse = avatar.avatar_url;
Toast.makeText(LoginActivity.this, "Returned " + returnedResponse, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<Avatar> call, Throwable t) {
call.cancel();
Toast.makeText(LoginActivity.this, "Please check your network connection", Toast.LENGTH_LONG).show();
}
});
}
And NodeJS
app.post('/users/avatar', type,
function (req, res) {
var filePath = __dirname + '/uploads/avatar.jpg';
fs.appendFile(filePath, req.body.image, function () {
res.end('file uploaded');
});
});
This is all I see in body object at NodeJS side.
"{"headers":{"namesAndValues":["Content-Disposition","form-data; name=\"image\"; filename=\"pic.jpg\""]}}"
Don't understand where is the image here and how to save it ??
You need some extra middleware to handle multipart/form-data (upload of binary data). You can take a look at the multer module for example.