How to set multiple queryString parameters in com.mashape.unirest.http.Unirest - java

Hi I am new Rest and was developing API where in request parameters i get comes from client and it is different each time. I will then have to call another API. I want to write one method to get JSON data from 3rd party API. I checked online and all examples were same. I am using Unirest follpwing is what I have done
HttpResponse<JsonNode> response = Unirest.get("https://api.stackexchange.com/2.2/questions").
header("accept", "application/json").
queryString("order","desc").
queryString("sort", "creation").
queryString("filter", "default").
queryString("site", "stackoverflow").
asJson();
Currently I have written all the queryString values.
Is there a way I can dynamically do this like put it in a map and give it to the method.

Yes, you can pass it a Map (Java source). The method signature is
public HttpRequest queryString(Map<String, Object> parameters)

Related

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.

OVH JAVA API using Get request with parameters

am trying to create a web interface to interact with OVH's telephony API ovh telephony api using the official JAVA wrapper OVH java wrapper.
I am trying to use a GET endpoint with parameters. this is the endpoint:
GET /telephony/{billingAccount}/line/{serviceName}/statistics
Parameters:
timeframe: string;
type : string
This is how I am doing the call:
api.get("/telephony/{myBuildingAccount}/line/{myServiceNumber}/statistics", "timeframe=daily&type=maxDelay", true);
But I am getting an error 400 bad signature.
Could someone help me with this ?
The API of the java wrapper specifies that the api.get method receives as the second parameter (in the three parameters version of api.get) the GET body; but you are passing a string containing the URL parameters:
api.get("/telephony/{ACCT}/line/{NUM}/statistics", "timeframe=daily&type=maxDelay", true);
Since the request you need does not require a body and does require the parameters in the URL, you need to use the following invocation:
api.get("/telephony/{ACCT}/line/{NUM}/statistics?timeframe=daily&type=maxDelay", true);
Pay attention that {ACCT} and {NUM} must be replaced by the actual account and service number values in that first string. Also, notice the parameters are appended directly into the string URL.
Hope this helps.

REST web application: what is the role of XML/JSON?

I am currently learning about REST applications, and particularly Java implementations of REST.
I am unsure of what role JSON or XML plays in in REST?
An example to show my current understanding:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
data passed back to service class and is then shown on the UI to user.
Where does JSON or XML fit into this process?
If we divide your 5th step...
1) data is returned from service in a certain format
2) UI receives it in that format and display it on the screen.
This format is XML or JSON or even plain text. This is the Accept type you mention when making a call from UI, and set the response header in service.
JSON stands for Javascript Object notation, hence if the response is in JSON format, you can directly use it as a javascript variable by just parsing it using JSON.parse. The Accept type is actually depends on your requirement. For most of the cases JSON is preferred, as it is easily converted to JS object.
It is the format that the data is returned from the service to the front end.
The transmission of data between the front end and the api is done in JSON and/or XML.
So, simplisticly...
the user asks for some data, through some web page, and the web page asks the RESTful API for the specific data, the api sends the web page the data as JSON, then the web page manipulates that and displays it or does whatever it needs to do with that data.
That is a general way to describe its role
A Method inside the controller is shown below which give json response
#RequestMapping(value = "/getSomething", method = RequestMethod.POST)
public #ResponseBody String getSomething(HttpServletRequest req)
{
JSONArray jsonArr = new JSONArray();
Collection someList = new ArrayList();
someList = someService.getsomeList(req); // here you get the response from service class to controller
Iterator iter = categoryList.iterator();
while (iter.hasNext()) // iterate the colleection
{
JSONObject jsonObj = new JSONObject();
SomeClass someObj = (SomeClass) iter.next();
jsonObj.put("name", someObj.getName());
jsonArr.put(jsonObj);
}
return jsonArr.toString(); // return jsonstring as response
}
This is how it can be processed in view (Say JSP). Here an ajax call made to controller and response set to the field in the page.
$.ajax({
url : "getSomething.htm", //request send to controller
type : "POST",
data : {
'someData' : data
},
success : function(data) {
var arr = JSON.parse(data);
response($.map(arr, function(item) {
return {
value : item.name, //setting the value to the view
};
}));
}
});
Hope this helps!
As other have said, in your example JSON/XML fits at the end of the chain (almost), when data is returned from the server to the client.
Think of JSON and XML (and other formats) as a type of box. Some boxes are made of plastic, some are made of cardboard since they serve different purposes.
JSON/XML are types of "boxes" for the data you are sending/requesting to/from the server.
In your example:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
Data from DB is "translated" from the server's data format ("type of box") into a more common format (like JSON or XML)
Data in JSON/XML format is sent to the front-end for displaying purposes
Think of it this way: if there wasn't a common format for people/systems to refer to, then if you query an Oracle database you would need to be able to understand that format. If you then had to query a Sybase database, then you would need to be able to understand that as well.
To solve this, you can pick a "common" format (a box that it's easier to fit in more trucks, as opposed to a box that can only be transported by a specific type of truck) and thus make it easier to "transport" that data around.
So in essence, JSON/XML is just a way of representing data, and as such it can be used to represent data that was originally in other "hard to read" format and make it easier to read or work with.
For example by returning your DB objects as JSON you can display them in a web page because most web page frameworks understand JSON as opposed to very few of them natively understanding Oracle/Sybase formats (there are drivers to do this but it is beyond the scope of this toy example).
You can also use it to communicate with other servers that also understand JSON (like third-party APIs for example) and thus if servers A and B have different data representations (internally one is Oracle backed and the other is Sybase backed) they can still talk to each other using a "common" format like JSON.

Using Olingo v2 Java as client for PATCH to OData v2 service

I'm trying to use Olingo to provide a client for interacting with an OData service (also written in Olingo). I'm trying to send a PATCH. However, the standard validation routines are kicking in and if I do not include those elements of the entity that are marked as non-nullable using the standard Olingo tools, I get an error.
in https://olingo.apache.org/doc/odata2/tutorials/OlingoV2BasicClientSample.html it says:
With an HTTP MERGE/PATCH it is also possible to send only the to be updated data as POST Body and omitting the unchanged data. But this is (currently) not shown within this sample.
Unfortunately I'm not sure how to do this, there, doesn't seem to be anywhere to flag to the EntityProvider.writeEntry method that it is a PATCH not a POST/PUT
EntityProviderWriteProperties properties = EntityProviderWriteProperties
.serviceRoot(rootUri).omitJsonWrapper(true).contentOnly(true)
.build();
// serialize data into ODataResponse object
ODataResponse response = EntityProvider.writeEntry(contentType,
entitySet, data, properties);
At this point in my code I get an error if "data" does not contain an entry for my non-nullable fields. The response also returns null values for all the attributes of the entity that aren't in my "data".
I deal with this by manipulating the response to remove all entries not in my "data" after the "standard" generation, but imagine that there must be a better way, even if I can't see it. Any suggestions on how to deal with this?
You have to create an "ExpandSelectTreeNode" which contains only the name of the selected properties to be serialized.
Assuming that your data is a HashMap with the values you can use following code as an example to start from:
// data = new HashMap<>();
ExpandSelectTreeNode node = ExpandSelectTreeNode.entitySet(entitySet)
.selectedProperties(new ArrayList<String>(data.keySet())).build();
EntityProviderWriteProperties properties = EntityProviderWriteProperties
.serviceRoot(rootUri).omitJsonWrapper(true).contentOnly(true)
.expandSelectTree(node)
.build();
// serialize data into ODataResponse object
ODataResponse response = EntityProvider.writeEntry(contentType,
entitySet, data, properties);
Best Regards
Is the contenttype from the client application/json-patch+json ?

Elasticsearch: send JSON query string via Java client?

I am new to Elasticsearch. I read Elasticsearch's Java client APIs and am able to build query and send it to the Elasticsearch server via the transport client.
Because my query is quite complex with multi-level filters and I notice that it is cumbersome to build a query via the Java client. I feel that it is much simpler to build a JSON query string and then send it over to the Elasticsearch server via a Java client.
Is this something Elasticsearch offers?
I do like what Elasticsearch Java API can do after receiving results such as scrolling over the results. I want to keep these features.
Thanks for any input and links!
Regards.
Did further research on Elasticsearch API and found out that Elasticsearch does offer this capability. Here is how:
SearchResponse scrollResp = client.prepareSearch("my-index")
.setTypes("my-type")
.setSearchType(SearchType.SCAN)
.setQuery(query) // **<-- Query string in JSON format**
.execute().actionGet();
You can no longer pass in string to the .setQuery function, however you can use a WrapperQueryBuilder like this:
WrapperQueryBuilder builder = QueryBuilders.wrapperQuery(searchQuery);
SearchRequestBuilder sr = client.prepareSearch().setIndices(index).setTypes(mapping).setQuery(builder);
I'd recommend using the Java API, it is very good once you get used to it and in most cases it is less cumbersome. If you look through the Elasticsearch source code you will see that the Java API Builds the JSON under the hood. Here is an example from the MatchAllQueryBuilder:
#Override
public void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(MatchAllQueryParser.NAME);
if (boost != -1) {
builder.field("boost", boost);
}
if (normsField != null) {
builder.field("norms_field", normsField);
}
builder.endObject();
}
ElasticSearch has built in capabilities to do exactly what you need, in an organized manner.
To answer your question, please see this link (the material is gone on elastic's site, so it might no longer work):
https://web.archive.org/web/20150906215934/https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/search.html
All you have to do is build a simple file which contains your search template i.e complex search query.
It can be a simple json file, or a text file.
Now you simply pass in your parameters, through your java code.
See the example in the link, it makes things amply clear.
Bhargav.

Categories

Resources