I have a post method in API, I want to post the data to the API as JSON raw. When I am testing from postman it is working correctly. From my its getting different response.
Map<String, String> paramObject = new HashMap<>();
paramObject.put("username", "jino");
paramObject.put("password", "12345");
paramObject.put("confirmpassword", "12345");
paramObject.put("email", "jino#gmail.com");
paramObject.put("phone", "1234567898");
UserService service = RetrofitInstance.getRetrofitInstance().create(UserService.class);
Call<ResponseBody> call = service.signUp(paramObject);
Service
#POST("addnewuser.php")
Call<ResponseBody> signUp(#Body Map<String, String> body);
Pass JsonObject instead of Map:
public interface RetrofitService {
#POST("addnewuser.php")
Call<ResponseBody> signUp(#Body JsonObject body);
}
Create it as following:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", "jino");
jsonObject.addProperty("password", "12345");
jsonObject.addProperty("confirmpassword", "12345");
jsonObject.addProperty("email", "jino#gmail.com");
jsonObject.addProperty("phone", "1234567898");
And call your Retrofit service:
Call<ResponseBody> call = service.signUp(jsonObject);
Related
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);
Retrofit converts POST in GET request when URL is like this
https://www.example.com/index.php?route=api/account/login
Found the solution
#FormUrlEncoded
#POST("index.php")
Call<String> login(#QueryMap(encoded=true) Map<String, String> options,#Field("email") String username,#Field("password") String password);
and calling will be like this
Map<String, String> map = new HashMap<>();
map.put("route","restapi/account/login");
Call<String> call = mAPIService.login(map, email, password);
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>
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.
I'm working on an Android project which needs a JSONObject for the body of my POST request.
After putting the keys and values of the JSON I got the following line:
{
"xxxx":"zzzzzzz",
"yyyy":"uuuuuuu"
}
But the server got the following:
{
"name_value_pairs": {
"xxxx":"zzzzzzz",
"yyyy":"uuuuuuu"
}
}
I've already tried a JSONStringer but it wasn't really helpful because the Content-Type of the request is application/json.
UPDATE
I'm not trying to construct a JSONObject because it's already done by using the following line of code (the same given by #osayilgan):
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("xxxx", "zzzzzzz");
jsonRequest.put("yyyy", "uuuuuuu");
Here is not the problem. The interface described below is used to communicate with the server.
public interface MyService {
#Headers({"Content-type: application/json",
"Accept: */*"})
#POST("/test")
void testFunction(#Body JSONObject jsonObject, Callback<Response> callback);
}
The server got the request with the second JSON as Body which is disappointing. I note that the key name_value_pairs is automatically added to the object.
Does anybody know how can I fix this?
Issue:
Retrofit by default uses GSON to convert HTTP bodies to and from JSON. The object which is specified with #Body annotation will be passed to GSON for serialization, which basically converts the JAVA object to JSON representation. This JSON representation will be the HTTP request body.
JSONObject stores all the key-value mapping in a member variable by name nameValuePairs.
Here is an excerpt of JSONObject implementation:
public class JSONObject {
...
private final Map<String, Object> nameValuePairs;
...
}
When you pass JSONObject to #Body annotation, this JSONObject is seraliazed, hence the HTTP request body contains : {"nameValuePairs": "actual JSON Object"}.
Solution:
Pass the actual JAVA object to #Body annotation, not it's corresponding JSONObject. GSON will take care of converting it to JSON representation.
For e.g.
class HTTPRequestBody {
String key1 = "value1";
String key2 = "value2";
...
}
// GSON will serialize it as {"key1": "value1", "key2": "value2"},
// which will be become HTTP request body.
public interface MyService {
#Headers({"Content-type: application/json",
"Accept: */*"})
#POST("/test")
void postJson(#Body HTTPRequestBody body, Callback<Response> callback);
}
// Usage
MyService myService = restAdapter.create(MyService.class);
myService.postJson(new HTTPRequestBody(), callback);
Alternative solution:
If you still want to send raw JSON as HTTP request body, then follow the solution mentioned by Retrofit author here.
One of the suggested solution is to use TypedInput:
public interface MyService {
#POST("/test")
void postRawJson(#Body TypedInput body, Callback<Response> callback);
}
String json = jsonRequest.toString();
TypedInput in = new TypedByteArray("application/json", json.getBytes("UTF-8"));
myService.postRawJson(in, callback);
Use com.google.gson.JsonObject instead of org.json.JSONObject.
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("xxxx", "zzzzzzz");
jsonRequest.put("yyyy", "uuuuuuu");
Change to
JsonObject jsonRequest = new JsonObject();
jsonRequest.addProperty("xxxx", "zzzzzzz");
jsonRequest.addProperty("yyyy", "uuuuuuu");
Then in interface
public interface MyService {
#Headers({"Content-type: application/json",
"Accept: */*"})
#POST("/test")
void testFunction(#Body JsonObject jsonObject, Callback<Response> callback);
}
JSONObject class keeping the values in LinkedHashMap with the variable name of nameValuePairs, When Gson trying to convert the JSONObject's instance into JSON,
GSON keeps the structure(which has the variable nameValuePairs). That causing this problem.
you have to covert JSONObject to JsonObject of GSON
follow this way
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject)jsonParser.parse(actualjsonobject.toString());
then pass in body
HashMap<String,Object> body=new HashMap();
body.put("content",jsonObject);
Thanks to 13KZ, pointed me in the right direction, and to flesh it out here is what I now have to solve this issue.
Definitions
private JsonObject gsonResultTwoWeek;
private JsonObject gsonResultDay;
private JsonObject gsonResult;
Initialise
gsonResult = new JsonObject();
gsonResultDay = new JsonObject();
gsonResultTwoWeek = new JsonObject();
Use
gsonResultDay.addProperty(epoch, value);
where data is a string and value is an int in my case and is in a for loop to add multiple values
And then to pull it all together
gsonResult.addProperty("accounts", 2);
gsonResult.add("todaydata", gsonResultDay);
gsonResult.add("2weekdata", gsonResultTwoWeek);
Finally my interface
public interface ApiInterface {
#POST("/groupdata")
void postGroupData(#Body JsonObject body,Callback<StatusResponse> cb);
}
What hits my server is this
{"accounts":2,"todaydata":{"1423814400":89,"1423816200":150,"1423818000":441},"2weekdata":{"1423699200":4869,"1423785600":1011}}
My solution is based on 13KZ's
public class MyRequest {
#SerializedName(Constants.ID)
private String myID;
#SerializedName(Constants.PARAM_ANSWERS)
private JsonObject answers;
public MyRequest(String id, Hasmap<String, String> answers) {
this.myID = id;
this.answers = new JsonObject();
for (String s: answers.keySet()) {
this.answers.addProperty(s, answers.get(s));
}
}
}
JSONObject jsonRequest = new JSONObject();
try {
jsonRequest.put("abc", "test");
jsonRequest.put("cba", "tye");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("jsonobject", "onClick: "+jsonRequest);
(result: {"abc":"test","cba":"tye"})
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject)jsonParser.parse(jsonRequest.toString());
Log.d("jsonobjectparse", "onClick: "+jsonObject);
(result: {"abc":"test","cba":"tye"})
Once you are put the values into the jsonObject pass to the jsonParser it will solve the issue
thats all. enjoy your coding.
nameValuePairs in retfrofit error
get this type
{
"nameValuePairs": {
"email": "mailto:test1#gmail.com",
"password": "12345678"
}
}
need this type
{
"email": "mailto:test1#gmail.com",
"password": "12345678"
}
#POST("login")
suspend fun getLogin(#Body jsonObject: RequestBody) : Response<LoginModel>
In Repository Class
Add this line for conver in json utf-8 fomat
val body = jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
class LoginRepository constructor(private val retrofitService: RetrofitService) {
suspend fun getLogin(jsonObject: JSONObject): NetworkState<LoginModel> {
val body = jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
val response = retrofitService.getLogin(body)
return if (response.isSuccessful) {
val responseBody = response.body()
if (responseBody != null) {
NetworkState.Success(responseBody)
} else {
NetworkState.Error(response)
}
} else {
NetworkState.Error(response)
}
}
}
It appears that you are attempting to transmit the actual JSONObject rather the the JSON text-string representation of the object. A look at the specification for the JSONObject class shows that you should be using the .toString() method to get the JSON text representation of the data structure kept by the JSONObject. Thus, you should be able to change:
public interface MyService {
#Headers({"Content-type: application/json",
"Accept: */*"})
#POST("/test")
void testFunction(#Body JSONObject jsonObject, Callback<Response> callback);
}
to:
public interface MyService {
#Headers({"Content-type: application/json",
"Accept: */*"})
#POST("/test")
void testFunction(#Body String jsonObject.toString(), Callback<Response> callback);
}
The only change being JSONObject jsonObject to String jsonObject.toString().
Alternately, you could brute force it by just taking the string that you have have of the JSON and replace '"name_value_pairs": {' with '' and the last '}' in the string with ''. JSON is just a string of text. Other than it being inelegant, there is no reason that you can not manipulate the text. Those two replacements will result in a valid JSON text-object. The whitespace indentation won't look correct to a human, but a machine parsing the JSON string does not care if the whitespace is correct.