How do I make async http get requests in Java? - java

I wrote a program where I call many http get request. It takes like half a minute till all the get requests are done but it needs to be done within a second, this can be achieved with calling this method asynchronously, right? But how?
This is what my get request looks like:
public static String dataRequest(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
String result = "";
while ((output = br.readLine()) != null) {
result += output;
}
conn.disconnect();
return result;
}
I tried using RxJava but I couldn't get it to work at all. I'm in a Maven JavaFx project. This method is in my getData class.

You can try using thread with ForkJoinPool
For example -> https://www.baeldung.com/java-fork-join

Related

How to pass Form data variables to the rest api call from stand alone java code

I got a situation to test the REST API's Delete call through Java code. I need to pass Form Data with 2 variables as below screenshot to the api request. someone please route me how to do that..
try {
URL url = new URL("http://localhost:8999/testsource");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("session", "Cii2vEBZDplu5fI9JNXiM5");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
Your question isn't very clear but I'll make an attempt to answer it based on the assumption that your form data contains two fields which are:
id
permanentDelete
String data = "id=the-id-goes-here&permanentDelete=yes-or-no-goes-here";
byte[] bytesToSend = data.getBytes(StandardCharsets.UTF_8);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(bytesToSend);

How to make multiple API calls in sequential order

I need to call two APIs A1 and A2 but not parallelly. A2 would get called only if A1 returns some flag value in its JSON response.
I'm aware of how to make an http call in java using Httpclient. one way is to write one code to make first call and parse its response and again use the same code to make another call.Is their any other smart way which automate this process for us where I will pass both the request and the condition on which second one need to call like it is possible in Rxjava
Follwing is the Rxjava code snippet (Reference : (RxJava Combine Sequence Of Requests))
api1.items(queryParam)
.flatMap(itemList -> Observable.fromIterable(itemList)))
.flatMap(item -> api2.extendedInfo(item.id()))
.subscribe(...)
How can I accomplish this in Java? Is there any Java feature that already exists and will allow me to make a multiple sequential call?
I tried searching for existing solutions but they were not in Java.
You can use HttpURLConnection to do an API call.
Check response and accordingly trigger another call.
Something like this
public static void main(String[] args) throws IOException {
String response1 = sendGET("http://url1");
if(response1 != null && response1.contains("true")){
String response2 = sendGET("http://url2");
}
}
private static String sendGET(String url) throws IOException {
URL obj = new URL(url);
StringBuffer response = new StringBuffer();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
return response.toString();
}

Consuming Rest API using java

I have code a java script to consume API response. But I am getting a bad request whenever I am trying to run it.
Kindly help me how to consume API through java.
Here I am trying to generate JWT token....
Please find the code below..
public static void main(String[] args) throws Exception {
URL url = new URL("URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
try {
String jsonData1 = "{\"grant_type\":\"aksa\"}";
String jsonData2 = "{\"username\":\"dkssdsk\"}";
String jsonData3 = "{\"password\":\"xE2w04kC1a7S\"}";
String jsonData4 = "{\"scope\":\"mksssl,/\"}";
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.write(jsonData1.getBytes());
output.write(jsonData2.getBytes());
output.write(jsonData3.getBytes());
output.write(jsonData4.getBytes());``
output.flush();
System.out.println(output);
// Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));`enter code here`
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Response code:" + connection.getResponseCode());
System.out.println("Response message:" + connection.getResponseMessage());
}
}
Your code writes:
{"grant_type":"aksa"}
{"username":"dkssdsk"}
{"password":"xE2w04kC1a7S"}
{"scope":"mksssl,/"}
This is not valid JSON. There are many JSON validators (including web pages you can copy/paste into) you could use to show this.
Test your service using a tool such as Postman. Once you have it working, ensure that your program writes the same content as the body configured in Postman.

Java Post Connection Using Try with Resources

I want to implement the code for handling POST requests using try with resources.
Following is my code:
public static String sendPostRequestDummy(String url, String queryString) {
log.info("Sending 'POST' request to URL : " + url);
log.info("Data : " + queryString);
BufferedReader in = null;
HttpURLConnection con = null;
StringBuilder response = new StringBuilder();
try{
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(queryString);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
log.info("Response Code : " + responseCode);
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch(Exception e){
log.error(e.getMessage(), e);
log.error("Error during posting request");
}
finally{
closeConnectionNoException(in,con);
}
return response.toString();
}
I have the following concerns for the code:
How to introduce conditional statements in try with resources for the above scenario?
Is there a way to pass on the connection in try with resources? (It can be done using nested try-catch blocks since URL and HTTPConnection is not AutoCloseable, which itself is not a compliant solution)
Is using try with resources for the above problem is a better approach?
Try this.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable conc = () -> con.disconnect()) {
// add request headers
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(queryString);
}
int responseCode = con.getResponseCode();
try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
// receive response
}
}
() -> con.disconnect() is a lambda expression which execute con.disconnect() at finally stage of the try statement.
1: You can use conditional statements inside try with resources statement also. Unfortunately you have to define new variable for this block and cannot use a predefined variable. ( variable in in your code)
try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) {
// your code for getting string data
}
2: I'm not sure HttpUrlConnection is AutoCloseable, So it might be a good idea to call the disconnect() yourself. I'm open to any suggestion on this one.
3: try with resources will definitely help you in managing the resources. But if you're confident that you're releasing the resources properly after use, then your code is fine.

HttpURLConnection multiple requests

I am new at REST api and I am trying simple code.
URL url = new URL("https://A.B/C");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
problem is, that I am trying to make multiple requests with same connection and I am struggling. Only possible solution I've "found" is to open new connection and create new buffered reader. I found that very inefficient. Is there any way, please, how can I recycle my opened connection and just update values over time?

Categories

Resources