I'm writing an application using the public Tumblr API, just for fun. I have set up my oauth keys, and I have the URL for accessing my blog's info. I was wondering how I could take the JSON-encoded data from that page and turn it into Strings for working with.
To be clear, if I wanted a blog's title, I could send a request to this URL and select the data for the title.
Thanks!
I've used Restlet for retrieving JSON data from a rest service. Below is the sample
Representation entity = new ClientResource("your url").get();
JsonRepresentation jsonRepresentation = new JsonRepresentation(entity.getText());
JSONObject jsonObject = jsonRepresentation.getJsonObject();
Related
I have to send a query with some headers and graphQL variables as a POST call to a GraphQL API in java. I also have to send some headers and authentication parameters in the query. Right now, I am doing a manual call in POSTMAN, but I want to do this programmatically. Can you guys help me where to start off. My query and variables are as follows
query sampleQuery($param: SampleQueryParams!, $pagingParam: PagingParams) {
sampleLookup(params: $param, pagingParams: $pagingParam) {
ID
name1
name2
}
}
And my GraphQL variables are as follows :
{"param": {"id": 58763897}, "pagingParam": {"pageNumber": 0, "pageSize": 10 } }
I have no clue where to start at. Could you guys please help
Below is a typical graphql endpoint for a java backend
There are 2 basic flows here
1 an endpoint for http request that can handle the graghql query as a string and a map / json representation of the query's input variables
2 the graphql wiring for the backend that collates and returns the data
the backend would typicaly have an endpoint that looks like this (1)
public Map<String, Object> graphqlGET(#RequestParam("query") String query,
#RequestParam(value = "operationName", required = false) String operationName,
#RequestParam("variables") String variablesJson) throws IOException {...
note we have 3 inputs
a query string,
a string usually json for the querys variables
an optional "operationName"
once we have parsed these input parameters we would typically send them to the graphql implementation for the query
which could look like this (1)
private Map<String, Object> executeGraphqlQuery(String operationName,
String query, Map<String, Object> variables) {
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query(query)
.variables(variables)
.operationName(operationName)
.build();
return graphql.execute(executionInput).toSpecification();
}
here the graphql object has all the wiring to return the data
So a solution is just to post the correctly formatted input parameters to the backend
I often use android and a http client that works with older android versions so a post request in kotlin could look like this as a very simple example
val client = HttpClients.createDefault()
val httpPost = HttpPost(url)
val postParameters = ArrayList<NameValuePair>()
postParameters.add(BasicNameValuePair("query", "query as string"))
postParameters.add(BasicNameValuePair("variables", "variables json string"))
httpPost.entity = UrlEncodedFormEntity(postParameters, Charset.defaultCharset())
val response = client.execute(httpPost)
val ret = EntityUtils.toString(response.getEntity())
please note the implementation for the http post with be dependent on the way the backend java implementation is set up
for the basic http client and post setup many good examples here
How to use parameters with HttpPost
possibly related
graphql allows for a introspection flow which publishes details on the query structure the implementation supports
more info here
https://graphql.org/learn/introspection/
[1] https://github.com/graphql-java/graphql-java-examples
I would recommend using graphql-java-codegen plugin for these purposes.
It provides a possibility to generate classes based on the schema which you can supply to any HTTP client.
For example, GraphQL server has following schema and we want to perform productById query:
type Query {
productById(id: ID!): Product
}
type Product {
id: ID!
title: String!
price: BigDecimal!
}
graphql-java-codegen will generate all classes required for you to perform a query:
// preparing request
ProductByIdQueryRequest request = new ProductByIdQueryRequest();
request.setId(productId);
// preparing response projection (which fields to expect in the response)
ProductResponseProjection responseProjection = new ProductResponseProjection()
.id()
.title()
.price();
// preparing a composite graphql request
GraphQLRequest graphQLRequest = new GraphQLRequest(request, responseProjection);
// performing a request with the constructed object
ProductByIdQueryResponse responseBody = restTemplate.exchange(URI.create("https://product-service:8080/graphql"),
HttpMethod.POST,
new HttpEntity<>(graphQLRequest.toHttpJsonBody()),
ProductByIdQueryResponse.class).getBody();
// Fetching a serialized object from response
Product product = responseBody.productById();
More examples can be found on GitHub: https://github.com/kobylynskyi/graphql-java-codegen#supported-plugins
My web clients send GET requests with URL query parameters. The receiving App can only accept POST requests with JSON body. I would like to embed a jetty servlet to the receiving App which converts GET requests to POST request, with url parameters being converted to json format body.
Input GET url for example: http://localhost:8081/?key_1=value_1&key_2=3value_2...&key_n=value_n
Expected POST json payload: {"key_1":"value_1", "key_2":"value_2", ..."key_n":"value_n"}
Could you please illustrate how to implement such functions?
I`ve worked with other programming languages, but am completely new to java. I really really appreciate your help.
Thanks and best regards,
Fischlein
You can read all the query string parameter and put it into HashMap. Then serialize this hashmap using jackson-json api or google gson api.
Jackson Reference Url :
http://wiki.fasterxml.com/JacksonHome
Read the parameters from the get request, create a json string and post it with a utility library like http://hc.apache.org/httpclient-3.x/
I am desperately trying to send an HTTP post to authenticate to twitter via JAVA but I keep getting HTTP 400 response code.
this is the HTML Code for the form that I want to use:
Sign in Remember me · Forgot password?
New to Twitter?
I am using JSOUP to try to access the class "signin" from the form at the top. I want to do that because I want to then use this code:
Element loginform = doc.getElementByClass("signin");
Elements inputElements = loginform.getElementsByTag("input");
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("session[username_or_email]"))
value = username;
else if (key.equals("session[password]"))
value = password;
paramList.add(new BasicNameValuePair(key, value));
}
This code will not work because the "loginform" class must be "getElemenById" instead of "getElementByClass", but the thing is, in the form, the "signin" is a class.
So my question is how do i get inputElements from a class instead of an id? I need this so that I can extract the parameters to send a valid HTTP POST to twitter so that I can authenticate an account.
ALL help is greatly appreciated
The power in JSoup is utilizing CSS selectors to handle parsing HTML. Take a look at the examples on jsoup.org.
For your specific example, try:
doc.select("input.signin")
Where the tag.class or tag#id or combine with other selectors as shown in the documentation.
I need to use some from from a php web service which rendering its data by serializing json in java play framework 1.2.x. What i am doing just using play WS function. and i am getting data from that service. But when I try to get it with JSONObject it throws excepiton which is so normal, because the returned data does not look a json format well. Any body who knows any workarounds or solution would be appreciated.
HttpResponse htp = WS.url("http://www.geoplugin.net/php.gp?ip=78.171.90.49").get();
System.out.println(htp.getContentType()+"\n"+htp.getStatusText()+"\n"+htp.getString());
The returned data :
a:18:{s:17:"geoplugin_request";s:12:"78.171.90.49";s:16:"geoplugin_status";i:200;s:16:"geoplugin_credit";s:145:"Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\'http://www.maxmind.com\'>http://www.maxmind.com</a>.";s:14:"geoplugin_city";s:8:"Istanbul";s:16:"geoplugin_region";s:8:"Istanbul";s:18:"geoplugin_areaCode";s:1:"0";s:17:"geoplugin_dmaCode";s:1:"0";s:21:"geoplugin_countryCode";s:2:"TR";s:21:"geoplugin_countryName";s:6:"Turkey";s:23:"geoplugin_continentCode";s:2:"EU";s:18:"geoplugin_latitude";s:7:"41.0186";s:19:"geoplugin_longitude";s:9:"28.964701";s:20:"geoplugin_regionCode";s:2:"34";s:20:"geoplugin_regionName";s:8:"Istanbul";s:22:"geoplugin_currencyCode";s:3:"TRY";s:24:"geoplugin_currencySymbol";s:15:"YTL";s:29:"geoplugin_currencySymbol_UTF8";s:3:"YTL";s:27:"geoplugin_currencyConverter";s:6:"2.2669";}
You are accessing the PHP endpoint. You need to hit this URL instead:
http://www.geoplugin.net/json.gp?ip=78.171.90.49
I have some forms and databases that will fill up some POJO's with data. Using Json (gson) I"m going to upload the data to my web server. The server will send back a responses that will eventually be placed back in objects.
My question is, should I encode/decode my objects to json and then pass strings back and forth to my WebApi class? Or should I pass my WebApi class my object and have it pass back an appropriate response object (based on the method I call.)?
So at when I call my Api that has all the http conection stuff in it, it would look something like this.
myWebApi postSomeData( jsonData ); //
Should jsonData be a pojo that will be encoded into json string inside myWebApi or should I encode it into json and pass in a string.
Or in otherwords
String postSomeData( String jsonData){
web code here..
}
or
ResponsePojo postSomeData( PostData myData){
...
myMapper.MapFrom(myData); //converts pojo to json
...
webcode
}
At some point there will be images included in the data needed to be uploaded.
I would recommend using json for data transfer, it will make your services technology independent.
You can use flexjon to serialize java objects in a pretty direct way on the server side.
For images you will need to do post http POST anyway, this should be done separately from data submit since an error in a image upload should not result in data loss. Typically you'll associate the id of your data object in the uploaded image (or reversly), so you need to insert your object to db and wait for the response to insert the dependency id to your image.
Best Regards,
Zied Hamdi
http://1vu.fr