How to use response object in kotlin - java

it was to ask how I can access different JSON objects in kotlin (they are inside the response)
I'm a newbie, it was to ask what is the best way to handle response objects
Fuel.post("usuario/login").jsonBody("{ \"email\" : \"cristian#admin.com\" , \"password\" : \"123456\"}")
.response { request, response, result ->
//println(response); // body:{token:34urfd9sf9dudu9sj}
println(response.body.token) //error "token" doesn't exist
}
This code is kotlin in android studio
in response I get several things, one of them is the "token" I thought that to access I only wrote response.token But it doesn't work :(

You need to extract the token json object in order to access it's value.
Something like the following will work
println(JSONObject(response.body).get("token"))

Related

Rest api design for an API which can consume three different type of json request

I have a input field or you can assume its a question, for which the user interaction can be of 3 types.
Text
Selection (multichoice)
Image upload (multiple medias)
I want to understand what should be the standard way to accept these responses.
I was thinking to have an API and request like below for Selection
http://example.com/input/{id}/response
Request Sample
{
"selections": [id1, id2]
}
for text type
http://example.com/input/{id}/response
Request Sample
{
"inputValue": "some input provided"
}
for media type
http://example.com/input/{id}/response
Request Sample
{
"files": [
{"name":"medianame", "type":"mediaType"}
]
}
But then if user wants to add a new file to the existing response, there need to be another API
http://example.com/input/{id}/response/{responseId}/upload
This doesn't seem right and readable, what could be the possible best design solution ?

Using the NCDC's Climate Data Online API with Java

I have never used a RESTful API. I want to use this API to get historical weather data, but I can't find a simple tutorial taking me from end to end making an app that uses a RESTful API in Java. I'm not sure what steps I should take to get the data.
The steps listed on the getting started page are not Java specific, so I'm not sure how to use that info. I have requested a token and got it, so I'm good on that front.
What I need help with is getting a minimal example showing how, with just a token and formatted URL, you can get JSON data from the API.
Some things I've looked into are javax.ws.rs and jersey client, but I'm not sure how to use those either.
Thanks in advance :)
Using Fetch you can do:
fetch(url, {options})
.then(data => {
// Do some stuff here
})
.catch(err => {
// Catch and display errors
})
Where the url is the one from the getting started page.
And you can get whatever data you need from data.
Say you need to save just the name in a local var, then you do:
.then(data => {
name = data.name
})

Android Retrofit - send dynamic number of POST parameters

I need to send a dynamic number of POST parameter values to an endpoint (there could be 1 or there could be 50). All of them will have the same key value.
Is this possible? I can't seem to figure out how to create a RequestBody that encompasses something like this, even when I try to construct it in plain text.
I have the list of strings prepared for it, but I just don't know how to create this kind of thing. The endpoint works in PostMan when I input a lot of post form parameters with the same key value, so the endpoint is setup properly for it. I'm just not sure if Retrofit supports this kind of thing, and I cannot seem to find any info around it.
I'm currently working with Java instead of Kotlin. Thoughts?
You can also pass multiple field parameter to your request like this:
#FormUrlEncoded
#POST("/oauth/access_token")
Call<YourResponseObject> sendData(
#FieldMap Map<String, String> params
);
The map can take variable number of args.
So you can pass data like:
/*
map = { "field1_key"="value1", "field2_key"="value2", "field3_key"="value3", ...}
*/
retrofit().create(YourInterface.class).sendData(mapOfFields)
p.s: retrofit() is a method that returns a Retrofit instance to work with.

Java Jersey-client: witing test a GET method

I want to write a unit test for GET method.I have a GET request that returns a json file of when I request path localhost:9090/application/a/b:
{
name: a,
Age:b
}
I want to write unit test using jersey client. I tried writing as such:
Response response = target("a/b").request(MediaType.APPLICATION_JSON).get();
The objective is to retrieve from the GET response and assert the returned json with an expected value:
assertEqual(expected value:{name: a, Age:b},returned json from response)
However, I am not quite sure how I can write this. Can someone guide me on this? I have been searching through many code samples but mostly it is for POST request so I am not sure how this is implemented for GET request.
Edit: I am not required to post anything (I can just grab most code sample for POST) What I am trying to do is just to invoke a call using the path without sending any json document or object and have it returned to me a response in json. After that, I am supposed to grab this json response, and then assert the object with an expected document. The part that I need guidance on is writing the right Response line of code. Also, since my test class has to inherit a jersey client parent, I am expected to use the Response class. I couldnt find any example like this online. That is why I am here to ask.
Thanks in advance

Play! 2+ Adding JSON support in a RESTfull way

I'm used to do ROR, but I need to make a RESTfull WebService in a Java environnement. So I decided to try it with Play! since it really look like a great idea.
So I'm trying to find a way to add JSON to my already existing firstapp done following those instruction : http://www.playframework.org/documentation/2.0.3/JavaTodoList
What I want is something working similarly to ROR. At least, I want to be able to ask for JSON support by :
calling a .json URL
using "Accept: application/json" Header
So I tried some dirty thing like that :
JsonNode json = request().body().asJson();
if(json != null) {
return ok(Json.toJson(Task.all()));
}
return ok(
views.html.index.render(Task.all(), taskForm)
);
And it's obviously not working right now...
I need to detect wich type the client is requiring. I saw some people were adding dirty routes like that :
POST /bars BarController.index()
GET /bars.json BarController.indexJSON()
But it will clearly not support client using header to specify json request...
So, what I need is some kind of way to find out if there is any Header specifing content-type or Accept application/json. If it is so, BarController.index() would return BarController.indexJSON()...
All in all, it would be pretty much similar to ROR wich do :
respond_to do |format|
format.html # index.html.erb
format.json { render json: #bars }
end
All in all :
Does anyone have gone through the same reasoning than me and had reach an end ?
So I resolved my problem by using to function in controller, like this :
public static Result index()
public static Result indexJSON()
Then I added routes :
GET /tasks controllers.TaskController.index()
GET /tasks/json controllers.TaskController.indexJSON()
I would have preferred task.json but it wouldn't have allowed /tasks/:id.json ...
And for Header support, you need to check in your classic function if there is no header :
public static Result index() {
if (request().getHeader(play.mvc.Http.HeaderNames.ACCEPT).equalsIgnoreCase("application/json") || request().getHeader(Http.HeaderNames.CONTENT_TYPE).equalsIgnoreCase("application/json")) {
return indexJSON();
}
else {
return ok(
views.html.index.render(Task.all(), taskForm)
);
}
}
End that's all folks !
Does anybody have a better solution ? I don't like this one very much... Because I'm going to repeat many code ...

Categories

Resources