I want to push and receive msgs using the Pushbullet api in java https://docs.pushbullet.com/v9/#http . The problem I am facing is that I really have no idea how to do anything related to apis, On the website it says you can do a request that goes like this:
curl --header 'Authorization: Bearer <your_access_token_here>' https://api.pushbullet.com/v2/users/me
using curl. what if I want to do it in java? what would I do? is it just something like getting the URL and adding 'Authorization: Bearer <your_access_token_here>' like this:
https://api.pushbullet.com/v2/users/me Authorization: Bearer <your_access_token_here> because it doesn't seem so.
this is the code I am working on:
HttpURLConnection urlConnection = (HttpURLConnection) new URL("https://api.pushbullet.com").openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json; utf-8");
there is something very simple I really don't understand here. Please give every step in your code or explanation
CodePudding user response:
You can write your own code using class HttpURLConnection, but there already third party http client libraries that can make it much simpler for you to do so. Here are some options:
Apache Http client
OK Http client
Also there is by far less known MgntUtils library that has Http client as well, and that one is very simple to use. Here is how your code would look like:
HttpClient client = new HttpClient();
client.setContentType("application/json; utf-8");
client.setRequestProperty("Authorization", "Bearer <your_access_token_here>");
try {
client.sendHttpRequest("https://api.pushbullet.com/v2/users/me", HttpClient.HttpMethod.GET);
System.out.println(client.getLastResponseCode() " " httpClient.getLastResponseMessage());
}catch(IOException ioe) {
System.out.println(client.getLastResponseCode() " " httpClient.getLastResponseMessage());
}
And you are all set. Here is the JavaDoc for HttpClient class. The library can be obtained as Maven artifact from Maven Central and from Github (including source code and Javadoc)
