inexperienced in java. Fumbling my way through a REST API client - java

I'm cobbling a small android app together that I want to use for our team. All it is doing is calling to a REST API endpoint and hitting a bunch of queries. Status, alerts, some monitoring information. Pretty simple. But I have spent 3 days staring at every site on Google that explains how to make a REST API call in Java, get back the JSON, and then store it as something like a hash where I can then just reference the JSON elements by name. I wrote a desktop version in Python and I'm thinking something like where Python just parses it into a DICT. So far I have some code. I'm not even sure if it works because I'm stuck with what to do next:
protected void getJSON() {
String url = "http://192.168.8.29/api/v1/version";
try {
URL hmAPIEndPoint = new URL(url);
HttpURLConnection myConnection = (HttpURLConnection) hmAPIEndPoint.openConnection();
if (myConnection.getResponseCode() == 200) {
// Success
// Further processing here
Log.d("getJSON", "Got a 200 back from the openConnection()");
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
// I need jsonReader to be something I can reference like jsonReader['version_id']
jsonReader.close();
myConnection.disconnect();
} else {
Log.e("getJSON", "Didn't register a 200 response. Actual: " + myConnection.getResponseCode());
}
} catch (MalformedURLException mfe) {
Log.e("getJSON", mfe.getStackTrace().toString());
} catch (Exception e) {
Log.e("getJSON", e.getStackTrace().toString());
}
}
From here there are like 500 sites that tell me to just parse the json line by line but that seems... stupid. Is there a way that I can get the jsonReader thing into an object like a described above?
Thanks in advance for your help.

Option 1
You can go with Retrofit network library.
It will convert all your json to POJO.
Sample tutorial
https://medium.com/#prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23
Option 2
Try to convert inputstream to POJO with help of GSON library
Gson dependency
implementation 'com.google.code.gson:gson:2.8.5'
Sample tutorial
http://www.acuriousanimal.com/2015/10/23/reading-json-file-in-stream-mode-with-gson.html

Related

Volley JSON Object Request for POST-ing an array, having a (string) tag and a JSON object

After looking at many examples available on Stack Overflow, I still haven't been able to figure out how to make it work out in my case yet. So, could you please provide me with some guidelines wherever possible? Specifically, I have already built a JSON array containing a tag and a JSON object, which should look like below when being posted (including the square brackets "[]"):
[
"location",
{
"coordinateA":12.45817,
"coordinateB":23.9195856
}
]
The corresponding JAVA code is as follows:
JSONObject CoordinatesFinalObj = new JSONObject();
JSONObject Location = new JSONObject();
try {
CoordinatesFinalObj.put("location-one", LocationOne);
} catch (JSONException e) {
e.printStackTrace();
}
try {
LocationOne.put("coordinateA", 12.45817);
LocationOne.put("coordinateB", 23.9195856);
} catch (JSONException e) {
e.printStackTrace();
}
When I POST-ed such the JSON array to our server using Volley JSON Object Request, it always returned the error 417. I actually did something similar by posting a Python array with a tag and a JSON object inside without any problems. And there are no special requirements of the http request header as imposed by our server.
JsonObjectRequest CoordinatesJsonObjectReq = new JsonObjectRequest(Request.Method.POST,
url, **CoordinatesFinalObj**, new Response.Listener<JSONObject>()...).
So, my question here is: Is Volley JSON Object Request a good fit for this purpose or I shall simply switch to use a string-based POST method (e.g. HttpURLConnection though it is a deprecated module). I am very confused why it is not working here...

How can I somehow "store" a json file in a Spring-Boot program so my web app then reads this json

Basically, I'm writing my first Spring-Boot program, and I have to get a list of products stored on a JSON file to display each product using VueJS (I know how to use Vue, I just need to get the JSON data somewhere in the webpage or smth)
I spent last 3'5 hours looking at tutorials about consuming JSON's and POST stuff and none helped.
Lets call your file config.json.
In a typical maven project, keep your file at
src/main/resources/config.json
In your code, read it like
try {
ClassPathResource configFile = new ClassPathResource("config.json");
String json = IOUtils.toString(configFile.getInputStream(), Charset.forName(Util.UTF_8));
} catch (IOException e) {
String errMsg = "unexpected error while reading config file";
logger.error(errMsg, e);
throw new Exception(e);
}
After this, use Jackson or GSON to read the json into an object. From there you can either reference it directly as a static attribute or as an attribute in component as per your use case.
Hope this code will work for you
public class JsonReader{
public static void readFromJson() throws Exception {
InputStream inStream = JsonReader.class.getResourceAsStream("/" + "your_config_file.json");
Map<String, String> keyValueMap =
new ObjectMapper().readValue(inStream, new TypeReference<Map<String, String>>() {});
inStream.close();
}
}
You might need to add the maven dependency for ObjectMapper()

JAVA Delete API with Array String Body

Sorry in advance for my googled english,
I work with an API and I make a JAVA software that allows to use it.
I need to make a DELETE and the software.
I have to perform a deletion, and with the supplied software to test the API, I am shown that I have to add the line in a body to remove it, like this :
["email","Termine","13/03/2018 09:52:20",etc...,""].
The body must contain a String Array with all the contents of the line to delete.
I can make it work in the test software.
However I can not understand how to make a DELETE with JAVA. I can make it work in the software test. That's what I did for now:
public static String delete(String json, String nomUrl) throws IOException {
URL url = new URL(baseUrl + "survey/"+ nomUrl + "/data");
//String json = "[\"Marc#Houdijk.nl\",\"Contacte\",\"10/04/2018 11:30:05\",\"Avoriaz\",\"Office de Tourisme\",\"Accueil OT\",\"Neerlandais\",\"Semaine 6\",\"Periode 2\",\"16\",\"\",\"Hiver 2018\",\"BJBR-CDQB\",\"04/12/2018 14:15:13\",\"04/12/2018 14:15:13\",\"04/12/2018 14:15:13\",\"\",\"Direct\",\"\",\"\",\"\"]\n";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("DELETE");
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Accept","application/json");
con.setRequestProperty("Authorization","Bearer "+token);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
StringBuilder responce = new StringBuilder();
responce.append("\\nSending 'DELETE' request to URL : ").append(url);
responce.append("\nResponse Code : ").append(responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
responce.append("\n").append(inputLine);
}
in.close();
return responce.toString();
}
I was inspired by what I did for the post and the get. But I do not see how to add a body correctly with my String Array to my delete function because it doesn't work, and the internet did not help me ...
Thank you in advance for your help !
EDIT : Finally, my code works. So if you want to delete with body, you can use this code. However, the problem comes from the json: I'm french, so was some accents on my words and special characters. After cleaning my string, everythings works.
EDIT : Finally, my code works. So if you want to delete with body, you can use this code. However, the problem comes from the json: I'm french, so was some accents on my words and special characters. After cleaning my string, everythings works.
You can create a POJO class with the fields required by RequestBody and send it to API, by Serializing the Object (Serialization means converting Java Objects into JSON and this can be done via GSON library). on API side you can easily get the ArrayList or whatever you want, just need to create same POJO class on server side as well, RequestBody will deserialize this JSON into Appropriate class, now via object of the class you can get whatever variables you want. Hope this helps.

Java - how to store a (multi-child) tree in file?

I'm working on an open-source, cross-platform pomodoro timer with statistics support.
For tasks, I have a tree data structure like this:
class Task {
String name;
int minutesWorkedOn;
int uniqueID;
Task parent;
...
ArrayList<Task> childTasks; //Note, not binary, but can have n-children.
}
(which is actually a bit bigger in practice)
I want to store this data structure in a file between sessions.
I was considering JSON or xml, and recurse for childTasks, or write all tasks out, one task per line and piece things back together by taskID's. But JSON/XML is not a hard-requirement, I'm just thinking out loud.
Some S.O answers mention serialization, but preferably I'd like to be able to see the stored data structure as is the case with JSON or XML. Also those two formats would make it easier to build reporting tools.
Considering I'm new to java and haven't worked with File/I/O before, can someone give me a tip/advise on which route to take here?
[edit]
The solution below works well. There is an issue with loops thou. I edited the code above, a task has a backwards link to it's parent. This causes gson to crash. I might ignore this field and fix it again after the data was loaded or maybe read some more about the tutorial.
The best and easy way is to use Gson to write/read the object to a file.
Write:
//Get the json serialization of the task object
GsonBuilder builder = new GsonBuilder();
//builder.setPrettyPrinting().serializeNulls(); //optional
Gson gson = builder.create();
String json = gson.toJson(task);
try {
//write json string to a file named "/tmp/task.json"
FileWriter writer = new FileWriter("/tmp/task.json");
writer.write(json);
writer.close();
} catch (IOException e) {e.printStackTrace();}
Read:
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("/tmp/task.json"));
//convert the json string from file back to object
Task task = gson.fromJson(br, Task.class);
} catch (IOException e) {
e.printStackTrace();
}

how to post in user's Streams using google plus api in java

I want to share some information in google plus wall from my application.and I am trying for moment.insert, But getting 400 error . Can somebody help me
#Override
public JSONObject getGooglePlusAddUseractivities(Object token) {
Token accessToken = (Token) token;
OAuthService service = createOAuthServiceForGooglePlus();
OAuthRequest request = new OAuthRequest(Method.POST,"https://www.googleapis.com/plus/v1/people/me/moments/vault");
request.addQuerystringParameter("alt", "json");
service.signRequest(accessToken, request);
JSONObject object=new JSONObject();
try {
object.put("kind","plus#moment");
object.put("type","http://schemas.google.com/AddActivity");
JSONObject obj1=new JSONObject();
obj1.put("kind", "plus#itemScope");
obj1.put("url","https://plus.google.com/me");
obj1.put("description","Sign up now to claim and redeem your credits while shopping! ");
obj1.put("image","http://invite.png");
obj1.put("contentUrl", "www.abcd.com");
obj1.put("thumbnailUrl", "http://logo1_favicon.png");
object.putOpt("target", obj1);;
}catch(Exception ex) {
ex.printStackTrace();
}
request.addPayload(object.toString());
request.addHeader("Content-Type", "application/json");
System.out.println("request : "+request.getBodyContents());
Response response = request.send();
String responseBody = response.getBody();
JSONObject googleJSON = null;
try {
googleJSON = new JSONObject(responseBody);
}
catch (JSONException e) {
System.out.println("can not create JSON Object");
}
getting 400 error ?? anyone can tell me..... where am wrong ..!!`
It isn't clear from the documentation, but you can't provide both the target.url and most other target metadata. This is currently opened as bug 485 in the issue tracking system - please go there and star the issue to make sure they properly prioritize a fix.
If you remove the target.url value and add a target.id value, it should work.
(As an aside, this does not post in the user's stream, but will post an App Activity in their app moment vault. They must manually share the activity if they choose.)
At this time, it is not possible to programmatically write to a user's Stream. As a developer, you have two options:
Write an AppActivity (formerly known as a Moment), which writes information to Google, but not to a Google+ Stream. These activities are visible at plus.google.com/apps, and will be used by Google in additional ways over time.
Create an Interactive Post Share button, which a user must initiate. However, you can pre-fill both the text of the post and up to 10 intended recipients. The user can make changes if they want and then perform the actual share. You can learn more at https://developers.google.com/+/web/share/interactive or by watching this Google+ Developers Live episode: http://www.youtube.com/watch?v=U4Iw28jWtAY.

Categories

Resources