how to make requests to an api - java

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

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() + " " + client.getLastResponseMessage());
}catch(IOException ioe) {
System.out.println(client.getLastResponseCode() + " " + client.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)

Related

Login to an application URL and POST Data using Java

I want to login to an authentication based application URL use those cookies/token to POST the json data to a mapping with java.
Login URL and POST URL are different and predefined in the application. (I can't change the URLs)
I tested using Postman and I can POST the data using the JSESSIONID and CSRF token from login Url but I have to do it using microservices.
I am new to java so I am not sure how to implement it. Can you please help with a sample code
What you need is Java Http client. There are several well known 3d party Http clients out there. Basically with each one you will need to replicate the same Http requests that you sent with your postman. For each request from postman (you are talking about 2 API end-points here: Login URL and some post method for exchange of the info using the token you received in from your login call) you can see the headers that you sent and you will need to send the same headers with your Http clients of your choice. Here are some recommended Http clients:
Apache Http Client. See links: HttpClient Overview and Apache HttpComponents - This is one of the most reliable and popular Http clients
OK Http Client. See links OkHttpClient, OkHttp Maven repository
Http client from MgntUtils library - This one is not well known client, and it does not provide all the width of functionality as the other ones, but its advantage that it is very simple in usage and it definitely would be good enough for what you need to acompllish. Disclaimer - MgntUtils library is written and maintained by me. Here is the Javadoc for HttpClient class. The MgntUtils library can be obtained as Maven artifacts and from Github (including source code and Javadoc). Here is an example of code. Lets say you called the Login API and obtained the token. So a call to your post method with MgntUtils HttpClient may look as something like this:
private static void bizServiceAdminAppTest() {
TextUtils.setRelevantPackage("com.mgnt.stam.");
HttpClient client = new HttpClient();
try {
client.setContentType("application/json; charset=UTF-8");
client.setRequestHeader("Accept", "*/*");
client.setRequestHeader("Authorization", "Bearer <token value>");
client.setRequestHeader("cookie", "<My cookie value>");
client.setConnectionUrl("http://my-server-address/some/path/");
String result = client.sendHttpRequest(HttpClient.HttpMethod.POST, "{\"some key\": 317809,\n" +
" \"key for list of values\": [\n" +
" \t2154377, 564\n" +
" ]\n" +
"}");
System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage() + "\n" + result);
} catch (IOException ioe) {
System.out.println(client.getLastResponseCode() + " " + client.getLastResponseMessage());
System.out.println(TextUtils.getStacktrace(ioe));
}
}

SonarQube Java Web API

I want to create QualityGates with the Web API in java.
String auth = username + ":" + password;
String authEncoded = Base64.getEncoder().encodeToString(auth.getBytes());
URL sonar = new URL("http://xxx.xxx.xxx.xx:9000/api/qualitygates/create");
HttpURLConnection conn = (HttpURLConnection) sonar.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authEncoded);
I dont seem to find anything in the topic of POST to web API.
In the Code i basically try to connect to the API with the Admin user authentication.
The Problem is, it doesnt matter what i do i always get ResponseCode 400. I know that it needs a name as a Property to create the QualityGate but that also doesnt seem to work.
My Question:
What do i need to do to use the POST method on web API's.
Best regards!
This isn't really a SonarQube question. It's a question about how to use POST apis. The API is returning a 400 error because you're not sending any data in the POST, and a POST expects data.
Read the answer to the following thread for hints on how to send data in a POST: Java - sending HTTP parameters via POST method easily .

How to send HTTP request from Java

i'm creating java module to parse JSON file.
To receive file i need to send HTTP request. When I use curl my request looks like this:
curl -X GET "https://***" -H "accept: application/json" -H "apikey: ***"
How can I send the equivalent HTTP request from Java
Java has a lot of options to work with HTTP.
Option 1
Since Java 9, there is a built-in HTTP client. So You can use it to create a request without any third-party libraries.
A simple example is something like this:
HttpRequest request2 = HttpRequest.newBuilder()
.uri(new URI("some url"))
.header("someHeader", "value1")
.header("anotherHeader", "value2")
.GET()
.build();
For more examples see here
Option 2
Use third party libraries, there are many: OkHttpClient, More "old-school" Apache Http Client (HttpComponents
Option 3
If you're using spring, you might consider using Spring's WebClient. There are also wrappers in spring like RestTemplate that can come handy, but it really depends on what would you like to work with.
Many clients are coming with http connection pools that should be properly set up.
In addition, in your example, I see that you work with https - all these clients support it but it should be properly set up.
If you are using Spring then try WebClient - it is a bit harder to understand in the begging (at least harder than RestTemplate) but it pays of since RestTemplate will be discontinued.
You can find an example here
https://www.baeldung.com/spring-webclient-resttemplate
#GetMapping(value = "/tweets-non-blocking",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Tweet> getTweetsNonBlocking() {
log.info("Starting NON-BLOCKING Controller!");
Flux<Tweet> tweetFlux = WebClient.create()
.get()
.uri(getSlowServiceUri())
.retrieve()
.bodyToFlux(Tweet.class);
tweetFlux.subscribe(tweet -> log.info(tweet.toString()));
log.info("Exiting NON-BLOCKING Controller!");
return tweetFlux;
}
Just be aware that this is non-blocking (e.g. asynchronous) solution so you won't get the response right away, but you subscribe to the request and then process the response when it is available. There are also blocking options in WebClient
Java has its own classes that allow you to send HTTP request. See class HttpURLConnection. However, I recommend using 3d party libraries that significantly simplify this task. Good libraries would be Apache Http client or OK Http client. I also can offer you to use another Open source library that has an HTTP client as well. It is called MgntUtils library and it is written by me. In this case your code would look something like this:
HttpClient workingClient = new HttpClient();
workingClient.setRequestProperty("accept", "application/json;charset=UTF-8");
workingClient.setRequestProperty("apikey", "***");
workingClient.setConnectionUrl("https://***");
ByteBuffer buffer =
workingClient.sendHttpRequestForBinaryResponse(HttpMethod.GET);
//or of your API returns contents of file as a string
String jsonStr = workingClient.sendHttpRequest(HttpMethod.GET);
After that, your ByteBuffer buffer or String jsonStr will hold the content of your JSON file. And now you can do whatever you need with it. Here is Javadoc for HttpClient class. The MgntUtils library can be obtained as maven artifacts here or on Github (including source code and Javadoc)

How to HTTP POST parameters with Android/Java?

I'm struggling to find good examples on how to POST key value pairs to a URL with Android in Java.
Here is what the Android documentation says (and pretty much every other example):
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
How do I implement writeStream?
Many other examples with POST put the parameters in the URL (a=1&b=2&c=3...), but then I could just use GET (?). And I don't want to place the parameters in the URL because that increases the chance of sensitive information to be logged on the server side.
Chrome POSTs data as such (body):
------WebKitFormBoundaryyr0AtYZxcOCCp7hA
Content-Disposition: form-data; name="parameterNameHere"
valueHere
------WebKitFormBoundaryyr0AtYZxcOCCp7hA--
Does the Android framework support this?
If not, are there any good libraries?
EDIT:
This is not a duplication of what was suggested. What was suggested does in no way answer the question, in that it does not show how to post with parameters, which is what this question is about.
There are many libraries out there that would help you achieve this. One of the libraries I use the most is OkHTTP. Include this library in your gradle and check the post from 'mauker' for an example on how to post
How to use OKHTTP to make a post request?

Java Client code to call restful web service

Can anybody tell me how to write a java client code to call restful web service with one parameter say email? I am trying the below code. But I am getting response as Success. Once this is success, I need the below XPHONE value. How to get this value?
XPHONE: 52-33-3669-7000
Here is the client code:
URL url = new URL("http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr=user.email");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Accept",
"application/json");
conn.connect();
I think you just missing response body handling.
There is nice article about rest-client code: article.
You can try using the JavaLite Http client:
JavaLite Http
Depends on how API is implemented value can be in response body or even in header, so this info you should know from specification or ask in dev team.
First try to check if everything works fine using CURL or better "Advanced rest client" ( its extension in Chrome browser) if it works, than just transfer flow to your code. How to use advanced rest client look here

Categories

Resources