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);
Related
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 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);
I am sending a POST request to server and my interface is this for Retrofit2 to convert it into JSON
public interface LoginService {
#POST("auth/signin")
#FormUrlEncoded
Call<CurrentUser> signin(
#Field("email") String email,
#Field("password") String password,
#Field("device_os") String device_os,
#Field("device_identity") String device_id
);
}
I want to see this request body in JSON format for the purpose of debugging.
Please help ! Thanks in advance .
check this answer
You can use a logging interceptor for it.
You can use Interceptor for OkHttpClient, then in the intercept method you would have:
...
Request.Builder builder = chain.request().newBuilder();
Request request = builder.build();
String bodyString = bodyToString(request);
...
private String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
if (copy.body() != null) {
copy.body().writeTo(buffer);
return buffer.readUtf8();
}
return "";
} catch (final IOException e) {
return "bodyToString error.";
}
}
My question is so similar to Retrofit 2.0 beta 4 response get IllegalArgumentException but its answer didn't help me.
I'm migrating from Retrofit 1.9 to 2.0.2.
I'm registering my app for messaging once launches.
/**
* Synchronous method to register GCM Token on Backend Server
*
* #return true, in case of success response, false otherwise.
*/
public boolean registerGCMToken()
{
...
try
{
Call<Response> call = mService.registerGCMToken(sessionId, this.ADDITIONAL_QUERY);
final Response response = call.execute().body(); // <<< Error points here
final DefaultResponse defaultResponse = DefaultResponse.newInstance(response);
return defaultResponse.isSuccess();
}
catch (IOException ignored)
{
}
return false;
}
My interface looks like:
#GET("my/url")
Call<Response> registerGCMToken(#Header(Constant.HEADER_WILDCARD) String accessToken,
#QueryMap Map<String, String> additionalQuery);
Once I launch the app I'm getting this error:
java.lang.IllegalArgumentException: 'retrofit2.Response' is not a
valid response body type. Did you mean ResponseBody?
and points to the line I mentioned above.
My newInstance method looks like:
public static final DefaultResponse newInstance(final Response response)
{
final DefaultResponse defaultResponse = new DefaultResponse();
if (response != null)
{
defaultResponse.status = response.code();
}
return defaultResponse;
}
So as you see, I need to know what is the HTTP status code. By changing Response generic to ResponseBody I'm not able to get http status code. What is your recommendation?
What i got while reading answers from the post suggested by you is that instead of this :
#GET("my/url")
Call<Response> registerGCMToken(#Header(Constant.HEADER_WILDCARD) String accessToken,
#QueryMap Map<String, String> additionalQuery);
Try :
#GET("my/url")
Call<ResponseBody> registerGCMToken(#Header(Constant.HEADER_WILDCARD) String accessToken,
#QueryMap Map<String, String> additionalQuery);
Because you are getting ResponseBody and not Response here :
final Response response = call.execute().body();
Like he did : How can I handle empty response body with Retrofit 2?
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.