Retrofit Post Request With Form data - android

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());
}
});
}`

Related

Multipart POST request using Retrofit

Android beginner here.
I am having an issue with Multipart POST request.
I am calling my API using POSTMAN and it returns code :200
but when i am calling it from my Application, it returns 503.
I found out that this can happen because POSTMAN sends it as multipart by default.
I looked through a lot of answers here but i couldn't relate them to my code.
How do i convert my current request into a multipart request?
Here is my interface:
#Multipart
#POST
Call<JsonObject> Login(#Url String url, #Body JsonObject LoginData);
My Interface is as follows :
public Call<JsonObject> Logincall(String teller_ID,String password,String ...}
/*somewhere around here i must do MultipartBody.Part...cant figure out where and how */
RetrofitAPI retrofitAPIObj = RETROBUILDER.create(RetrofitAPI.class);
JsonObject LoginData=new JsonObject();
LoginData.addProperty("teller_ID",teller_ID);
LoginData.addProperty("password",password);
LoginData.addProperty("branch",branch);
LoginData.addProperty("terminal",terminal);
LoginData.addProperty("isSecure",isSecure);
return retrofitAPIObj.Login(RetrofitURL.LOGIN, LoginData);
}
Thanks in advance
You can Call Api Format Like This There is parameter type Like JsonObject in post Method
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
if (!MNetworkUtil.isNetworkAvailable()) {
MToastUtil.show("网络不能连接");
return;
}
File file = new File(filePath);
String json = new Gson().toJson(new UploadHeadPicRequestModel());
if (!file.exists()) {
MToastUtil.show("文件不存在");
return;
}
progressDialog.show();
avatarSimpleDraweeView.setEnabled(false);
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
if (responseModel != null) {
String serverAvatarUrl = responseModel.data.headPicPath;
if (!TextUtils.isEmpty(serverAvatarUrl)) {
UserModel userModel = MUserManager.getInstance().getUser();
if (userModel != null) {
userModel.setAvatarUrl(serverAvatarUrl);
MUserManager.getInstance().updateOrInsertUserInfo(userModel);
MToastUtil.show("上传头像成功");
}
}
}
}
#Override
public void onFailure(int status, String failureMsg) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
MToastUtil.show((TextUtils.isEmpty(failureMsg) ? "上传失败" : failureMsg) + " : " + status);
}
});
}
you can create a multipart Body with additional properties by following.
public MultipartBody createMultiPartBody(){
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("teller_ID",teller_ID);
builder.addFormDataPart("password",password);
builder.addFormDataPart("branch",branch);
builder.addFormDataPart("terminal",terminal);
builder.addFormDataPart("isSecure",isSecure);
MultipartBody requestBody = builder.build();
return requestBody;
}
Now, by calling this method, you will be getting multipartBody which you can parse by following code.
public static void uploadCropImage(String url, RequestBody requestBody, Callback<BasicResponse> callback) {
UploadMultiPartData uploadMultipartData = retrofit.create(UploadMultiPartData.class);
Call<ResponseType> call = uploadCropImageApi.uploadCropImage(url, requestBody);
call.enqueue(callback);
}
this is the interface.
public interface UploadMultiPartData {
#POST(UPLOAD_URL)
Call<ResponseType> uploadMultiPartData(
#Url String url,
#Body RequestBody requestBody);
}

Unable to send header and multipart at the same time in Retrofit 2 in android

This is the code im using for multiple uploads to server.This format is working fine in POSTMAN and not working in by using retrofit2. Can anybody help me
#Multipart
#POST("/api/answers/save")
Call<ResponseBody> upload(#Header("Authorization") String
authorization,#Part("input_answer") RequestBody answer_string,#Part
List<MultipartBody.Part> files);
check this
#NonNull
private RequestBody createPartFromJsonString(String json_answers_string) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, json_answers_string);
}
check this , using this for converting file to multipart body
#NonNull
private MultipartBody.Part prepareFilePart(String attachment_name, String absolute_path) {
File file = new File(absolute_path);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData(attachment_name, file.getName(), requestFile);
}
This is used for multiple uploads
private void multipartUploadAudit(JSONObject json_object, List<String> FileNameWithAbsolutePath) {
progressBar.setVisibility(View.VISIBLE);
//convert jsonobject to string
Gson gson = new Gson();
String answers_string_json_obj = gson.toJson(json_object);
APIService mAPIService = ApiUtils.getAPIService();
List<MultipartBody.Part> parts = new ArrayList<>();
// add dynamic
for (int i = 0; i < FileNameWithAbsolutePath.size(); i++) {
String name = FileNameWithAbsolutePath.get(i).substring(FileNameWithAbsolutePath.get(i).lastIndexOf("/") + 1);
String names[] = name.split("\\.");
parts.add(prepareFilePart(names[0], FileNameWithAbsolutePath.get(i)));
}
// add another part within the multipart request
RequestBody answer_string = createPartFromJsonString(answers_string_json_obj);
// finally, execute the request
Call<ResponseBody> call = mAPIService.upload("Bearer " + sharedPrefUserData.getUserData().getAuthToken(), answer_string, parts);
// Call<ResponseBody> call = mAPIService.upload( description, parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
progressBar.setVisibility(View.GONE);
if (response.isSuccessful()) {
response.body(); // do something with that
Toast.makeText(AuditQuestionsLandingScreen.this, response.body().toString(), Toast.LENGTH_SHORT).show();
} else {
response.errorBody(); // do something with that
Toast.makeText(AuditQuestionsLandingScreen.this, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
progressBar.setVisibility(View.GONE);
internetConnectionChecker.serverErrorAlert();
Log.v("Upload_error:", t.getMessage());
Toast.makeText(AuditQuestionsLandingScreen.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
After long struggle i got my answer. i made a mistake by converting jsonobject to string by using gson. it added enveloped my string with
{"nameValuePairs": {}}
so i used this.
RequestBody.create(MediaType.parse("multipart/form-
data"),String.valueOf(json_object))

Why is no request made on retrofit call?

I want my android users to be able to upload a profile image to the django rest api. I use retrofit to handle the upload:
UserService
#Multipart
#POST("users/upload-profile-image/")
Call<ResponseBody> uploadProfileImage(#Part MultipartBody.Part image,
#Part("name") RequestBody name);
UserRepository
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload");
Call<ResponseBody> req = userServiceApi.uploadProfileImage(body, name);
req.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call,
#NonNull Response<ResponseBody> response) {
// Do Something
if (response.isSuccessful()) {
Log.d(TAG, "Successfully uploaded image");
} else {
eventBus.post(new FailUploadProfileImageEvent());
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
t.printStackTrace();
}
});
To instantiate the userServiceAPI
userServiceApi = ServiceGenerator.createService(UserService.class, token);
ServiceGenerator
// Actual digits replaced with X
private static final String BASE_API_URL = "http://XXX.XXX.X.XXX:8000/";
private static OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_API_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass, String token) {
if (token != null)
okHttpBuilder.authenticator(new TokenAuthenticator(token));
OkHttpClient client = okHttpBuilder.build();
builder.client(client);
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);
}
users/urls.py
url(r'^upload-profile-image/$', views.UserProfileUploadImageView.as_view(), name="upload_profile_image"),
When I run the android app, no request is made to the server, why?

retrofit2 upload file

I'm trying to upload a videofile from my app.
Here's what I've got so far:
public class Download extends Application {
public interface upload {
#Multipart
#POST("new")
Call<Response> send(#Part("myFile") RequestBody file);
}
public void uploadFile(File xfile) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.3")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestBody file = RequestBody.create(MediaType.parse("video/*"), xfile);
upload xUpload = retrofit.create(upload.class);
Call<Response> call = xUpload.send(file);
try {
Response result = call.execute().body();
}
catch (IOException e)
{
Log.d("TEST3", " didn't work ");
}
}
}
I get the following error retrofit2.Response' is not a valid response body type. Did you mean ResponseBody? for method upload.send any ideas
I've read up on the retrofit2 webpage and tried the main example they have for uploading a file but it didn't work for two reasons.
1. I couldn't find right ServiceGenerator
2. My file was found in the Gallery and I streamed its contents to a temporary file which I'm to upload, I can't access it directly from its URI... or can I with retrofit2?
i use to upload image from retrofit 2 like this,it worked correctly
File file = new File(image.getPath());
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("gallery", file.getName(), mFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), id);
final NetworkCall networkCall=new NetworkCall(this);
Call<ResponseBody> call = networkCall.getRetrofit(false).uploadImage( filename, fileToUpload);
call.clone().enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
here is my network call class:
public class NetworkCall {
Context context;
ProgressDialog progressDialog;
public NetworkCall(Context context){
this.context = context;
}
public IApi getRetrofit(boolean isShowLoading){
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectTimeout(0, TimeUnit.SECONDS).readTimeout(0,TimeUnit.SECONDS);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content_type","application/json")
.header("Accept", "application/json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
if (isShowLoading&&context instanceof BaseActivity)
showLoading();
// prepare call in Retrofit 2.0
IApi api = retrofit.create(IApi.class);
// Call<BaseResponce> call = api.callService(json);
//asynchronous call
// call.enqueue(this);
return api;
}
private void showLoading(){
try {
((BaseActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
public void dismissLoading(){
try {
((BaseActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.cancel();
progressDialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}
i use this in IApi class
#Multipart
#POST("events/file_upload.json")
Call <ResponseBody> uploadImage(#Part("event_id") RequestBody id,#Part MultipartBody.Part part);
hope it helps

Retrofit2 - How to upload image using retrofit in multipart?

I'm trying to upload image on server using retrofit2 beta 3. In response i'm getting success but image is not getting uploaded on server. I dont know where's i'm making mistake.
and
Header Type is Content-Type: application/x-www-form-urlencoded
My Interface
#Multipart
#POST("/uploadFile")
Call<ResponseBody> upload(#PartMap Map<String, RequestBody> params);
and the method i used for uploading is
Method for uploading Image and data
private void uploadFile() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface service =
retrofit.create(ApiInterface.class);
File file = new File(fileUri.getPath());
Log.e(TAG, "uploadFile: " + file.toString());
String fileName = "uploadFile\"; filename=\"" + file.getName();
final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
final RequestBody empsno = RequestBody.create(MediaType.parse("text/plain"), strEmpsno);
final RequestBody storsno = RequestBody.create(MediaType.parse("text/plain"), strStoreSno);
final RequestBody strlr = RequestBody.create(MediaType.parse("text/plain"), strLrno);
final RequestBody strtecq = RequestBody.create(MediaType.parse("text/plain"), strRecqty);
final RequestBody strtecv = RequestBody.create(MediaType.parse("text/plain"), strRecvol);
final RequestBody strtecw = RequestBody.create(MediaType.parse("text/plain"), strRecwgt);
final RequestBody strdmg = RequestBody.create(MediaType.parse("text/plain"), strDamageqty);
final RequestBody strlus = RequestBody.create(MediaType.parse("text/plain"), strLooseqty);
final RequestBody strdd = RequestBody.create(MediaType.parse("text/plain"), strDeliverydate);
final RequestBody strdt = RequestBody.create(MediaType.parse("text/plain"), strDeliverytime);
final RequestBody strrem = RequestBody.create(MediaType.parse("text/plain"), strRemarks);
final RequestBody strrec = RequestBody.create(MediaType.parse("text/plain"), strReceivedby);
final RequestBody strip = RequestBody.create(MediaType.parse("text/plain"), strIpaddress);
Map<String, RequestBody> oJSONObject = new HashMap<>();
oJSONObject.put("empsno", empsno);
oJSONObject.put("storesno", storsno);
oJSONObject.put("lrSno", strlr);
oJSONObject.put("recQty", strtecq);
oJSONObject.put("recVol", strtecv);
oJSONObject.put("recWgt", strtecw);
oJSONObject.put("damageQty", strdmg);
oJSONObject.put("looseQty", strlus);
oJSONObject.put("deliveryDate", strdd);
oJSONObject.put("deliveryTime", strdt);
oJSONObject.put("remarks", strrem);
oJSONObject.put("receivedBy", strrec);
oJSONObject.put("ipAddress", strip);
Call<ResponseBody> call = service.upload(oJSONObject);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e(TAG, "onResponse: " + response.isSuccessful());
if (response.isSuccessful()) {
Log.e(TAG, "onResponse: " + response.body());
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getLocalizedMessage());
}
});
}
in response response.isSuccessful()=true. My response is getting successful then where is my problem. Please help me to find the solution.
Other way i also tried but not getting success, same result in another way also
#Multipart
#POST("/uploadFile")
Call<Response> getDetails(#Part("empsno") RequestBody empsno,
#Part("storesno")RequestBody storesno,
#Part("lrSno")RequestBody lrSno,
#Part("recQty")RequestBody recQty,
#Part("recVol")RequestBody recVol,
#Part("recWgt")RequestBody recWgt,
#Part("damageQty")RequestBody damageQty,
#Part("looseQty")RequestBody looseQty,
#Part("deliveryDate")RequestBody deliveryDate,
#Part("deliveryTime")RequestBody deliveryTime,
#Part("uploadFile\"; filename=\"abc.jpg\" ") RequestBody part,
#Part("remarks")RequestBody remarks,
#Part("receivedBy")RequestBody receivedBy,
#Part("ipAddress") RequestBody ipAddress
and method i used here is
File file = new File(fileUri.getPath());
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploadFile", file.getName(), requestFile);
RequestBody empsno = RequestBody.create(MediaType.parse("text/plain"), strEmpsno);
RequestBody storsno = RequestBody.create(MediaType.parse("text/plain"), strStoreSno);
RequestBody strlr = RequestBody.create(MediaType.parse("text/plain"), strLrno);
RequestBody strtecq = RequestBody.create(MediaType.parse("text/plain"), strRecqty);
RequestBody strtecv = RequestBody.create(MediaType.parse("text/plain"), strRecvol);
RequestBody strtecw = RequestBody.create(MediaType.parse("text/plain"), strRecwgt);
RequestBody strdmg = RequestBody.create(MediaType.parse("text/plain"), strDamageqty);
RequestBody strlus = RequestBody.create(MediaType.parse("text/plain"), strLooseqty);
RequestBody strdd = RequestBody.create(MediaType.parse("text/plain"), strDeliverydate);
RequestBody strdt = RequestBody.create(MediaType.parse("text/plain"), strDeliverytime);
RequestBody strrem = RequestBody.create(MediaType.parse("text/plain"), strRemarks);
RequestBody strrec = RequestBody.create(MediaType.parse("text/plain"), strReceivedby);
RequestBody strip = RequestBody.create(MediaType.parse("text/plain"), strIpaddress);
ApixInterface xInterface = retrofit.create(AudexInterface.class);
Call<Response> podResponsecall = xInterface.getDetails(empsno, storsno, strlr, strtecq,
strtecv, strtecw, strdmg, strlus, strdd, strdt,
requestFile, strrem, strrec, strip);
podResponsecall.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
Log.e(TAG, "onResponse: " + response.isSuccessful());
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Successfully saved!!!", Toast.LENGTH_LONG);
Log.e(TAG, "onResponse: " + response.body().getResult());
uploadFile();
}
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getLocalizedMessage());
}
});
By using this method also response is successful but image not getting upload on server.
Thanks in advance
my solution is that:
first step.
#Multipart
#POST("Work/SendPic.ashx")
Observable<ImgBean> uploadImg(#Part MultipartBody.Part file);
second step.
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("img", file.getName(), requestBody);
UploadImg uploadImg = BaseRetrofit.getInstance().create(UploadImg.class);
and then, it is working.
What i have observed is there is some bug in Okhttp which does not upload image. Handle it like this:
#Multipart
#POST("api/chats/upload_chat_image")
Call<UploadChatItemResponse> getImageLink(
#Header("Authorization") String token,
#Part("productid") RequestBody productid,
#Part("touserid") RequestBody touserid,
#Part("image\";filename=\"image.*\" ") RequestBody image);
Notice the last part. You can create #PartMap for remaining items. But don't do it for files. Also, the first image in last part should be the key server is expecting while last image should be as it is.
RequestBody uploadImage = RequestBody.create(MediaType.parse("image/png"), compressed_image);
RequestBody productId = RequestBody.create(MediaType.parse("text/plain"), product.getProductid() + "");
RequestBody userId = RequestBody.create(MediaType.parse("text/plain"), otherUserInfo.getUserid() + "");
Call<UploadChatItemResponse> uploadChatImage = RestClient.getInstance(getApplicationContext()).getRestService()
.getImageLink(PrefUtils.getToken(ChatActivity.this), productId, userId, uploadImage);
uploadChatImage.enqueue(new Callback<UploadChatItemResponse>() {
#Override
public void onResponse(Call<UploadChatItemResponse> call, Response<UploadChatItemResponse> response) {
if (response.body() != null && response.body().imageLink != null) {
sendMessage(response.body().imageLink, new ChatItem.ChatType(false, ChatItem.ChatType.CHAT_TYPE_IMAGE, ChatItem.ChatType.CHAT_SUBTYPE_NO_SUBTYPE));
sweetAlertDialog.dismiss();
compressed_image.delete();
} else {
Toast.makeText(ChatActivity.this, "An error has occurred", Toast.LENGTH_SHORT).show();
sweetAlertDialog.dismiss();
compressed_image.delete();
}
}
#Override
public void onFailure(Call<UploadChatItemResponse> call, Throwable t) {
Toast.makeText(ChatActivity.this, "An error has occurred", Toast.LENGTH_SHORT).show();
sweetAlertDialog.dismiss();
compressed_image.delete();
}
});
Notice the type I have used while creating RequestBody for image.
Edit:
This is RestClient.java.
public class RestClient extends ContextWrapper {
private static final String BASE_URL = "https://www.restapi.in";
private APIService apiService;
private static RestClient restClient;
private static OkHttpClient okHttpClient;
private static final int READ_TIMEOUT = 100 * 1000;
private static final int CONNECTION_TIMEOUT = 100 * 1000;
private static final int CACHE_SIZE = 4;
private static final String CERTIFICATE_DOMAIN = "www.restclient.in";
private static final String[] CERTIFICATE_SHA = {"sha256/dkjabkjabcbakjbakjsbcabcahkcbakcbakcbakh=",
"sha256/ckjdcndkjcnjcnajcnajskcnakjcnakjcnaksjcna=",
"sha256/cjkacakjcbajcbasjkcbacjcbakcbcbakjbcjkacb="};
private RestClient(Context context) {
super(context);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkHttpClient(context))
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(APIService.class);
}
public static RestClient getInstance(Context context){
if(restClient==null)
restClient = new RestClient(context.getApplicationContext());
return restClient;
}
private static OkHttpClient getOkHttpClient(Context context){
if (okHttpClient == null) {
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(BuildConfig.DEBUG?HttpLoggingInterceptor.Level.HEADERS:HttpLoggingInterceptor.Level.NONE);
CertificatePinner.Builder certificatePinnerBuilder = new CertificatePinner.Builder();
for(String sha : CERTIFICATE_SHA)
certificatePinnerBuilder.add(CERTIFICATE_DOMAIN, sha);
okHttpClient = new OkHttpClient.Builder()
.cache(setCache(context))
.certificatePinner(certificatePinnerBuilder.build())
.retryOnConnectionFailure(false)
.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content-type", "application/json")
.header("Accept", "application/json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
})
.addInterceptor(logger)
.build();
}
return okHttpClient;
}
private static Cache setCache(Context context) {
int cacheSize = CACHE_SIZE * 1024 * 1024;
return new Cache(new File(context.getCacheDir(), "http"), cacheSize);
}
public APIService getRestService(){
return apiService;
}
}
Just remove Header Type
#headers({Content-Type: application/x-www-form-urlencoded})

Categories

Resources