POST raw data Using Retrofit - android

I'm trying to POST raw data using Retrofit.
I found many solution to POST JSON in Body using volley but the data I'm sending is not JSON.
my data is : {project_purpose: [EXECUTION]}
while hitting from the postman, I'm getting the data but not in android.
Please suggest me how to do this.
I'm trying to send as string but getting 500 in error code
I've also send the data in JsonObject, but not working..
Here is my code to call..
String bodyST = "{project_purpose: [purpose]}";
OR
JsonObject data = new JsonObject();
JSONArray jarray = new JSONArray();
jarray.put("EXECUTION");
data.addProperty("project_purpose", String.valueOf(jarray));
Call<JsonArray> call = apiInterface.getData(mAuthToken, "application/json", bodyST);

try this
I was facing the same problem when trying to POST data in raw form only and for this, i have wasted my whole day after that I got my solutions.
Your API interface should be like this:-
#POST(Constants.CONTACTS_URL)
Call<Object> getUser(#Body Map<String, String> body);
In your class where you are calling this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
try {
Map<String, String> requestBody = new HashMap<>();
requestBody.put("email", "davinder.codeapex#gmail.com");
requestBody.put("password", "12345678");
Call<Object> call=apiInterface.getUser(requestBody);
call.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
try {
JSONObject object=new JSONObject(new Gson().toJson(response.body()));
Log.e("TAG", "onResponse: "+object );
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
Output
logcat:
Postman
Note:-i am not using any model class to get data after, retrieving data you can use anyway to store data.

Just send your body as string
#PUT("your-endpoint")
fun yourRequsetFunction(#Body body : String) :Response<YourResponseType>

Related

post request with retrofit gets responce a s bad request in android

I am using https://docs.ngenius-payments.com/reference#hosted-payment-page for payment in android
Headers:
Add these headers to your request (note that you should replace 'your_api_key' with the service account API key in the Getting started section).
Header Value
Content-Type application/vnd.ni-identity.v1+json
Authorization Basic: your_api_key
Body / Form Data:
Add the following information to the form/body content of your request.
Example request (body):
JSON
{
‘realmName’: ‘ni’
}
these are the headers and content type and i created a post method using retrofit
public static Retrofit getRetrofitClient() {
//If condition to ensure we don't create multiple retrofit instances in a single application
if (retrofit == null) {
//Defining the Retrofit using Builder
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
}
return retrofit;
}
My api interface is
#POST("identity/auth/access-token")
Call<NgeniusPaymentAccessTokenModel> nGeniusAccessToken(#Header("content-type") String ContentType, #Header("authorization") String apiKey, #Body JsonObject object);
and i call it by
JsonObject postParam = new JsonObject();
try {
postParam.addProperty("realmName", "ni");
} catch (Exception e) {
e.printStackTrace();
}
Call call = apiService.nGeniusAccessToken(contentType, "Basic "+apiKey, postParam);
i am getting the responce as error telling its a bad request, how to solve this
You can try below code:
String contentType = "application/vnd.ni-identity.v1+json";
String authorization = "Basic: "+apiKey;
JSONObject postParam = new JSONObject();
try {
postParam.put("realmName", "ni");
} catch (JSONException e) {
e.printStackTrace();
}
Call call = apiService.nGeniusAccessToken(contentType, authorization, postParam);
this one worked for me i put all of the headers in a header map
creata a map
Map<String, String> stringMap = new HashMap<>();
try {
stringMap.put("Authorization", "auth");
stringMap.put("Content-Type", "CONTENT_TYPE");
stringMap.put("accept", "accept");
} catch (Exception e) {
e.printStackTrace();
}
api interface looks like
#POST("transactions/orders")
Call<ResponseBody> nCreateOrder(#HeaderMap Map<String, String> headers,String out, #Body JsonObject object);
now call it by
nCreateOrder(stringMap ,"out",jsonObject);

Error in sending POST request using retrofit

I have a json data to be sent using retrofit in android howerver it's not not getting sent to the server. I have used slim framework at the server side .
this is my interface in android client side
public interface RequestInterface
{
#Headers("Content-type: application/json")
#POST("/instituteRegister")
Call<InstRegServerResponse> sendInstRegData(#Body InstRegServerRequest
post);
}
this is the sign up method
> public void signup()
{
String regdName = _regdName.getText().toString();
String email = _email.getText().toString();
String password = _password.getText().toString();
Log.d("password", password);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface =
retrofit.create(RequestInterface.class);
InstRegServerRequest instRegServerRequest = new InstRegServerRequest();
instRegServerRequest.setiname(instituteName);
instRegServerRequest.setemail(email);
instRegServerRequest.setpassword(password);
Call<InstRegServerResponse> response =
requestInterface.sendInstRegData(instRegServerRequest);
response.enqueue(new Callback<InstRegServerResponse>()
{
#Override
public void onResponse(Call<InstRegServerResponse> call,
retrofit2.Response<InstRegServerResponse> response)
{
InstRegServerResponse resp = response.body();
Log.d("status:", "sign up success");
}
#Override
public void onFailure(Call<InstRegServerResponse> call, Throwable t)
{
Log.d(Constants.TAG,"signed up failed");
}
});
}
The error is the JSON data is not passed to the server
The api endpoint works correctly as i have tested it using postman
in the android logcat i get sign up success but at the server side I think the json is not passed correctly that's why i'm unable o write the data to the database
Try this.
#Headers("Content-Type: application/json; charset=UTF-8")
#POST("instituteRegister")
Call<InstRegServerResponse> sendInstRegData(#Body Map<String, Object> params);
Construct your JSON object using Map<String, Object>.
Example:
Map<String, Object> param = new HashMap<>();
param.put("YOUR_KEY", YOUR_VALUE);

Android json parsing can get json response from ws calling from Retrofit?

I am using retrofit lib because it's giving fast response.
But why need always one model class corresponding one ws response of parsing/calling web service using retrofit. Is it possible to get json response directly in my program?
You can wrap your response inside Response and then access the JSON data using the following:
call.enqueue(new Callback<ResponseBody>() {
#Override
onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
// Do your success stuff...
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Yes, you can. Use this as your api call:
Call<ResponseBody> yourMethod(). Then in your onResponse callback you can get json response via response.body().string(). See javadoc.

Get single JSON property value from response JSON using Retrofit 2

I am using Retrofit library (version 2.0.2 as of this writing).
I am making a GET call to a service which responds a big JSON object but I am only interested in one key:value pair in it.
How can I get just that instead of writing a whole new POJO class that matches the JSON response?
Example -
{
status_code: 34,
status_message: "The resource you requested could not be found.",
...,
...
}
I need only status code value (34 here).
Please note, I am just giving an example of this JSON object here. The real one I am dealing with is huge and I care about only one key:value pair in it.
Thanks in advance.
You can refer to the following:
#GET("/files/jsonsample.json")
Call<JsonObject> readJsonFromFileUri();
and
class MyStatus{
int status_code;
}
...
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("http://...")
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIService apiService = retrofit2.create(WebAPIService.class);
Call<JsonObject> jsonCall = apiService.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
String jsonString = response.body().toString();
Gson gson = new Gson();
MyStatus status = gson.fromJson(jsonString, MyStatus.class);
Log.i(LOG_TAG, String.valueOf(status.status_code));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
Debug screenshot

How to pass JSON object and retrieve JSON object in retrofit request in Android?

I need to pass Json in Post request using Retrofit. My Json looks like this:
{
"q": {
"reg": "IND",
"or": [
{
"duration": "12"
}
]
},
"sort": "recent"
}
I created pojo for above Json using jsonschema2pojo which is similar to this: RoomListing.java class
Now I need to make a post request. So I created an API
public interface RoomListingAPI {
#GET("/api/fetch")
void getRoomListing(#Header("x-parse-session-token") String
token, #Body RoomListing list);
}
Created a RestAdapter class
return new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
RoomListingAPI apiservice = restadapter.providesRestAdapter().create(RoomListingAPI.class);
Now I am little bit confused to send Json (Have a look at RoomListing.java) as post request and receive JSON in response ?
Any help would be appreciable.
Firstly, you need to change the annotation from #GET to #POST to do a POST request. Next, assuming you're using Retrofit 1.9.x, you need to do one of two things to get the resulting JSON response, depending on if you want a synchronous or asynchronous response:
Synchronous (on the current thread) - change void to be of the type of the pojo for the response, similar to how you've made your request object (e.g. ResponseType yourMethod(#Body RequestType object);
Asynchronous (on a different thread, with a callback) - add a Callback<ResponseType> to the end of the method, which will then be called on the successful, or unsuccessful, return of the request (e.g. void yourMethod(#Body RequestObject object, Callback<ResponseType> callback);
public interface RoomListingAPI {
#POST("/api/fetch")
void getRoomListing(#Header("x-parse-session-token") String
token, #Field("YOURFIELDNAME") String json);
}
//This method generates your json
private String yourJSON(){
JSONObject jsonRoot = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject2 = new JSONObject();
try{
jsonArray.put(jsonObject2);
jsonObject2.put("duration", "12");
jsonObject1.put("reg", "IND");
jsonObject1.put("or", jsonArray);
jsonRoot.put("q", jsonObject1);
jsonRoot.put("sort", "recent");
}catch (JSONException e){
e.printStackTrace();
}
return jsonRoot.toString();
}
RoomListingAPI apiservice = restadapter.providesRestAdapter().create(RoomListingAPI.class);
apiservice.getRoomListing("your_header_token",yourJSON())...
I hope you work but it should be something like this.

Categories

Resources