How to convert the json object response from retrofit success response? - android

I have worked with retrofit file upload. Here by using system.out.println I can track the response body. But can't convert the response to JSON object.
I hereby write my code. Kindly please let me know how do I parse and get the string value using retrofit success message and failure message.
ApiConfig:
public interface ApiConfig {
#Multipart
#POST("general/Candidate/fileUpload")
Call<ResponseBody> upload(
#Header("Authorization") String authorization,
#PartMap Map<String, RequestBody> map,
#Part("id") RequestBody id,
#Part("fileCount") RequestBody fileCount,
#Part("fileType") RequestBody fileType,
#Part("platform") RequestBody platform,
#Part("externalID") RequestBody externalID);
}
ServiceGenerator:
public class ServiceGenerator {
public static final String API_BASE_URL = "http://104.239.173.64/peoplecaddie-api/";
private static Retrofit retrofit = null;
private static OkHttpClient httpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new Gson()));
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
uploadFile1:
private void uploadFile1(Uri fileUri) {
progressDialog.show();
ApiConfig service =
ServiceGenerator.createService(ApiConfig.class);
File file = FileUtils.getFile(this, fileUri);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
Map<String, RequestBody> map = new HashMap<>();
map.put("fileContent0\"; filename=\"" + file.getName() + "\"", requestFile);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileContent0", file.getName(), requestFile);
String idStr = "1743";
String fileCountStr = "1";
String fileTypeStr = "SAMPLE";
String platformStr = "Android";
String externalIDStr = "portpolio";
RequestBody idReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), idStr);
RequestBody fileCountReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), fileCountStr);
RequestBody fileTypeReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), fileTypeStr);
RequestBody platformReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), platformStr);
RequestBody externalIDReq =
RequestBody.create(
MediaType.parse("multipart/form-data"), externalIDStr);
// finally, execute the request
Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
try {
System.out.println("Rrespppppp--->"+response.body().string());
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
Here upload file method I can track the response using. This works fine.
System.out.println("Rrespppppp--->"+response.body().string());
But while try to convert the JSON Object it will not work the error code is below. And please let me know how do i parse and get the success and failure response value using this code.
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
Log.e("retro", "retroFileResp------------------>" + profileFileUploadResponse);
Thanks in Advance.

**You have to use Gson to get JsonObject response like below.**
public interface getProfileInfo {
#GET("users/{userid}")
Call<JsonObject> getProfileData(#Path("userid") String userId);
}
private void getUserProfileInfo(String userId)
{
getProfileInfo postService=RetrofitApi.makeNetworkRequest().create(getProfileInfo.class);
Call<JsonObject> call = postService.getProfileData(userId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
System.out.println("user Info :" + response.body().getAsJsonObject());
setUserData(response.body().getAsJsonObject());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
System.out.println("Error :" + t.getMessage());
}
});
}

Modified your code. Please try. You will get json object in result
Call<ResponseBody> call = service.upload("817b6ce98fd759e7f148b948246df6c1", map, idReq, fileCountReq, fileTypeReq, platformReq, externalIDReq);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
try {
System.out.println("Rrespppppp--->"+response.body().string());
Log.e("response", "response------------------>" + response.body().string());
//JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
ResponseBody result = response.body();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});

Retrofit Response is already in json format you can get item by
{ "result": [{ "fileId": 852, "status": 1, "pcData": { "id": 635, "filename": "IMG_20161122_175344.jpg", "filepath": "uploads\/peoplecaddie\/files\/1743_1480742360_IMG_20161122_‌​175344.jpg" } }] }
String fileid=response.body().getresult(0).getFileId();
String status=response.body().getresult(0).getStatus();

You can only call response.body().string() once. From the ResponseBody docs --
The response body can be consumed only once.
You try to consume the body on both of the following two lines
Log.e("response", "response------------------>" + response.body().string());
JSONObject profileFileUploadResponse = new JSONObject(String.valueOf(response.body()));
You can read it once into a variable and reuse that --
final String body = response.body().string();
Log.e("response", "response------------------>" + body);
JSONObject profileFileUploadResponse = new JSONObject(body);
That should fix your problem, but if you don't want to go further and don't want to deal with creating the JSONObject yourself, one of the benefits of retrofit it does deserialization as well. You are already configuring a gson converter to your retrofit, so you should be able to update your call to --
#Multipart
#POST("general/Candidate/fileUpload")
Call<ReturnObject> upload(...)
where ReturnObject is the POJO you want to deserialize to. You will have to update your response handler as well, to expect a ReturnObject type.

Try this, It will work
Change Call Type as JsonElement
#GET("LoginAPI")
Call<JsonElement> getLogin(#Query("Username") String userName,
#Query("Password") String password);
Get Json object from the response
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONObject object = new JSONObject(response.body().toString());
textView.setText(object.toString());
} catch (JSONException e) {
e.printStackTrace();
textView.setText(e.getMessage());
}
}

Related

how to post raw json array to server in retrofit

every time i run this function onfaliure calls
json array
{"ORDER":[{"ORDER_DATE":"2020-09-08 01:28:11 PM","CUSTOMER_ID":"umersaleem_03334033313","PRODUCT_ID":"","QUANTITY":1,"DEAL_ID":"1","ORDER_TOTAL":"600.0"}
interface
#POST("/restaro/index.php/Home/insert_order_info")
Call<CheckloginModel> insertOrder(#Body JSONObject j);
function
retrofitApiInterface.insertOrder(orders)
.enqueue(new Callback<CheckloginModel>() {
#Override
public void onResponse(Call<CheckloginModel> call, Response<CheckloginModel> response) {
if (response.isSuccessful()) {
}
#Override
public void onFailure(Call<CheckloginModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Poor internet connection or device is Off ", Toast.LENGTH_SHORT).show();
}
});
}
api response
this the response when the data is inserted through postman
{
"status": 1,
"message": "new order added "
}
when i send it on postman the data is inserting need help thanks in advance
#Headers("Content-Type: application/json")
#POST("/restaro/index.php/Home/insert_order_info")
Call< CheckloginModel> insertOrder(#Body RequestBody body);
request body send with your json and send this request body to api.
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("value", "value");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody=RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonObject.toString());
I will only this line and pass requestbody Retrofit call and works for me
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject1.toString());
Call<CheckOutResponse> call = RetrofitClient.getInstance().getApi().postOrder(requestBody);
call.enqueue(new Callback<CheckOutResponse>() {
#Override
public void onResponse(Call<CheckOutResponse> call, Response<CheckOutResponse> response) {
CheckOutResponse checkOutResponse = response.body();
#Override
public void onFailure(Call<CheckOutResponse> call, Throwable t) {
}
});
Webservice class
#POST("yourAPiCall")
Call<CheckOutResponse> postOrder(#Body RequestBody requestBody);

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

How to send multiple images to server using retrofit 2.3.0 in android?

I tried below code to send multiple images to server through retrofit 2.3.0
but its not worked to me :
Map<String, RequestBody> multiPartMap = new HashMap<>();
multiPartMap.put("originalImgBlob",RequestBody.create(MediaType.parse("image/png"), mFiles.get(0)));
multiPartMap.put("img430Blog",RequestBody.create(MediaType.parse("image/png;base64"), mFiles.get(1)));
multiPartMap.put("img200Blog",RequestBody.create(MediaType.parse("image/png;base64"), mFiles.get(2)));
multiPartMap.put("img100Blog",RequestBody.create(MediaType.parse("image/png;base64"), mFiles.get(3)));
multiPartMap.put("blurResponseBlob",RequestBody.create(MediaType.parse("image/png;base64"), mFiles.get(4)));
and send this multipart data to server like this :
Call<JsonObject> stringCall = mServerUtilities.getStringClassService(getApplicationContext(), "").postImage(Singleton.getInstance().getUserRegDetailsRespModel().getMId(), ACTION_TYPE_UPLOAD_NEW_PIC,multiPartMap);
stringCall.enqueue(new retrofit2.Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, #NonNull retrofit2.Response<JsonObject> response) {
Log.d("fb_regist_response", "--->" + "" + response);
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
mUtilities.showAlert(t.getMessage(), getResources().getString(R.string.app_name));
Log.d("onFail_fb_regist_res", t.getMessage());
}
});
and this is the final retrofit interface:
#Multipart
#POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
Call<JsonObject> postImage(#Path("memberId") String memberId,
#Path("actionType") String actionType,
#PartMap Map<String, RequestBody> multipartTypedOutput);
I need to send multiple images to server through retrofit 2.3.30 only ,can anyone suggest me to do that
I got error: 204(no content )
Instead of using #Part try #Field
#Multipart
#POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
Call<JsonObject> postImage(#Part("memberId") RequestBody memberId,
#Part("actionType") RequestBody actionType,
#Part MultipartBody.Part[] multipartTypedOutput);
and in your Activity use this method to send the post
public void sendPost(String memberId, String actionType) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
MultipartBody.Part[] multipartTypedOutput = new MultipartBody.Part[imageModelArrayList.size()];
for (int index = 0; index < imageModelArrayList.size(); index++) {
Log.d("Upload request", "requestUploadSurvey: survey image " + index + " " + imageModelArrayList.get(index).path);
File file2 = new File(imageModelArrayList.get(index).path);
RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file2);
multipartTypedOutput[index] = MultipartBody.Part.createFormData("imageFiles[]", file2.getPath(), surveyBody);
}
RequestBody memberId1 = RequestBody.create(MediaType.parse("text/plain"), memberId);
RequestBody actionType1 = RequestBody.create(MediaType.parse("text/plain"), actionType);
apiService.postImage(memberId1, actionType1, multipartTypedOutput).enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("fb_regist_response", "--->" + "" + response);
dialog.dismiss();
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("onFail_fb_regist_res", t.getMessage());
dialog.dismiss();
}
});
}

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))

Retrofit POST raw string body

I am using Retrofit to send a POST request to a server. The body of the POST must be in the form jdata={"key1":"value1",...} along with a Content-Type header set to application/x-www-form-urlencoded. I found a similar question but the accepted answer is not working.
Here's what I tried -
My interface
public interface APIHandler {
#Headers("Content-Type: application/x-www-form-urlencoded")
#FormUrlEncoded
#POST(URL)
Call<ResponseBody> getdata(#Field("jdata") String jdata);
}
Call function
public void load() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("BASE_URL")
.addConverterFactory(GsonConverterFactory.create())
.build();
// prepare call in Retrofit 2.0
APIHandler iAPI = retrofit.create(APIHandler.class);
String requestBody = "{\"id\":\"value\",\"id1\":\"value2\"}"
Call<ResponseBody> call = iAPI.getData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> c, Response<ResponseBody> response) {
if (response.isSuccess()) {
ResponseBody result = response.body();
String gs = new Gson().toJson(result);
Log.d("MainActivity", "response = " + gs + " status: " + statusCode);
} else {
Log.w("myApp", "Failed");
}
}
#Override
public void onFailure(Call<ResponseBody> c, Throwable t) {
}
});
}
But I receive response = null and status = 200. What am I doing wrong? The expected response is only a string and not a JSON array.
I am leaving this here so that it helps someone.
The above code is correct. As I mentioned in the last line, a plain string response was expected. But since it is not a JSON response, the conversion probably did not work and the response was null. The only solution I could find was to directly convert the response to string -
try {
stresp = response.body().string()
Log.d("MainActivity", "response = " + stresp + " status: " + statusCode);
} catch (IOException e) {
//Handle exception
}
There might be a better way to handle this but that worked for me!
You can use like that. I have tested this and it working fine
public interface APIHandler {
#POST(URL)
Call<ResponseBody> getdata(#Body JsonObject body);
}
Request body:
JsonObject requestBody = new JsonObject();
requestBody.addProperty("id", "value1");
requestBody.addProperty("id1", "value2");
Prepare call in Retrofit 2.0
APIHandler iAPI = retrofit.create(APIHandler.class);
And Call function :
Call<ResponseBody> call = iAPI.getData(requestBody);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> c, Response<ResponseBody> response) {
if (response.isSuccess()) {
String result = response.body().string();
Log.d("MainActivity", "response = " + result);
} else {
Log.w("myApp", "Failed");
}
}
#Override
public void onFailure(Call<ResponseBody> c, Throwable t) {
}
});

Categories

Resources