How to call External API in for loop - java

I try to call API with different id as shown in following code. But it only executed for first run and stop. Can Anyone help how to solve this problem?
The size of the idArray is 2.
for (int i = 0; i< idArray.size(); i++){
String id = idArray.get(i);
Thread.currentThread().sleep(3000);
String myURI1 = "https://api.bulksms.com/v1/messages/"+id;
URL url1 = new URL(myURI1);
System.out.println(myURI1);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setDoOutput(true);
request1.setRequestProperty("Authorization", "Basic " + authEncoded);
request1.setRequestMethod("GET");
request1.setRequestProperty( "Content-Type", "application/json");
BufferedReader in1 = new BufferedReader( new InputStreamReader(request1.getInputStream()));
String inputLine1;
StringBuffer response1 = new StringBuffer();
while ((inputLine1 = in1.readLine()) != null) {
response1.append(inputLine1);
}
}

I would like you to refer #hgoebl answer to Single URLConnection to fetch only the first line in java using BufferedReader.
"HttpURLConnection cannot be reused, but it can reuse an open connection to the same server internally by setting the header Connection: keep-alive. It doesn't make sense if you connect to different servers, obviously.
"

Related

How to do non-GET requests on your own API

I followed this guide to create my own REST API. I am trying to consume my API that I built from the guide but I ran into some trouble when it came to using any request that wasn't a GET request. When I tried doing a delete request. (http://localhost:8080/api/v1/employees/3)
I would get a 405 error and I'm not sure why (I do not have any password protection in my local host). I want to understand how I can create requests other than GET. I tried using query parameters for my POST request, but it was unsuccessful.
I looked at all the other StackOverFlow Similar Questions and I couldn't find anything.
EDIT1: I am using a simple Java Application to do this.
This was the code I used in order to do my GET requests
String urlString = "http://localhost:8080/api/v1/employees";
try {
String result = "";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader (new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result += line;
}
rd.close();
System.out.println(result);
}
Try to replace this URLConnection conn = url.openConnection();
to this:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
you can use org.springframework.web.client.RestTemplate (rest-template) to consume rest api.
for delete, you can do something like
private void deleteEmployee() {
Map < String, String > params = new HashMap < String, String > ();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
}
please check https://www.javaguides.net/2019/06/spring-resttemplate-get-post-put-and-delete-example.html and https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html and https://www.baeldung.com/rest-template
hope these provide enough info

How to replicate curl command using java?

Precisely said I want to perform below curl action which returns json with java:
curl -H 'Client-ID: ahh_got_ya' -X GET 'https://api.twitch.tv/helix/streams'
This works just fine in linux shell.
below is my script trying to do above curl using java json:
{String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Client-ID","Ahh_got_ya");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("");
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
I am getting: java.io.FileNotFoundException: https://api.twitch.tv/helix/streams Response Code : 404
All replies are much appreciated.
Almost there! You are doing a GET call and do not need to make the connection writeable -- since you are not going to post. You need to remove that section there. Also - to get exactly what your curl call is doing, remove the Content-Type - since it is not used in the curl call. So your code adjusted should be:
{
String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//only 2 headers from cURL call
con.setRequestMethod("GET");
con.setRequestProperty("Client-ID","Ahh_got_ya");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
The reason for the 404 is if your request does not match what the service endpoint is expecting. Sending a POST request or other types of non-expect stuff will result is a request that does not match. Remove the extra output stuff and give it a go!
The way you state your question is a bit weird. But I assume you want to let a Java program make a cURL call of a JSON file. Now your linux terminal talks BASH not Java. So here is step 1.
You have to use a library.
Options are java.net.URL and/or java.net.URLConnection.
So #include one or either of those.
URL url = new URL("https://api.twitch.tv/helix/streams");
try (BufferedReader reader = new BufferedReader(new
InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Another thing you could mean is you want Java to generate JSON and access cURL trough Bash which isn't something I would advise anyone to do. If you feel like you have to it would be something like this.
public class ExecuteShellCommand {
public String executeCommand(String command) {
With the string set to cURL

How to Close HttpsURLConnection Java

I am trying to request data from the server using HttpsURLConnection; I currently have the server requiring the user to enter a username and password via a prompt. In a web browser after you enter the correct username and password, the browser would save the username and password as a session cookie in your browser so you can visit other pages within site without being prompted for your credentials. But for the client which is in Java, it does not save the username and password. I am trying to use .disconnect() to close the connection, but I keep getting the following error:
java.lang.IllegalStateException: Already connected
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3053)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestProperty(HttpsURLConnectionImpl.java:316)
My Java Code:
private static void sendPost(String _url) throws Exception {
String url = _url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
int responseCode = con.getResponseCode();
Auth(con);
if (responseCode == 200) {
label.setText("Sucssesfully Scanned: " + StudID.getText());
} else {
label.setText("Error, please scan again");
}
con.disconnect();
}
private static ArrayList<String> Get(String _url) throws Exception {
ArrayList<String> list = new ArrayList<>();
JsonParser parser = new JsonParser();
String url = _url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Auth(con);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
JsonElement element = parser.parse(response.toString());
if (element.isJsonObject()) {
JsonObject data = element.getAsJsonObject();
for (int i = 0; i < data.get("chapels").getAsJsonArray().size(); i++) {
JsonObject jObj = (JsonObject) data.get("chapels").getAsJsonArray().get(i);
list.add(jObj.get("Name").toString().replaceAll("\"", "") + " - " + jObj.get("Loc").toString().replaceAll("\"", ""));
}
}
return (list);
}
private static void Auth(HttpsURLConnection con){
String encodedBytes = Base64.getEncoder().encodeToString((BCrypt.hashpw("swheeler17", BCrypt.gensalt(10)) + ":" + BCrypt.hashpw("Trinity", BCrypt.gensalt(10))).getBytes());
con.setRequestProperty("authorization", "Basic " + encodedBytes);
}
Example of username and password prompt: https://chapel-logs.herokuapp.com/chapel
java.lang.IllegalStateException: Already connected
That exception means that you have attempted to set the property giving the authorization for the request after it has been sent.
This is probably where it happens:
int responseCode = con.getResponseCode();
Auth(con);
and Auth calls setRequestProperty.
Asking for the response code causes the request to be sent if if hasn't already been sent. (Obviously ... you can't get the response code until you get the response, and the server can't give you one unless the request is sent.)
To answer your question, calling disconnect on the connection will disconnect the connection.
But that's not what is causing your problem. The stacktrace shows clearly that the exception is happening when something is calling setRequestProperty.
Based off of Stephen C's answer I determined the swap the order of:
int responseCode = con.getResponseCode();
Auth(con);
So the working solution is:
Auth(con);
int responseCode = con.getResponseCode();
I'm assuming ResponseCode() creates a request to the server if a request has not already been made, otherwise ResponseCode() uses the pre-existing request. Upon further testing, I concluded there is no need to call .disconnect().

JSON String using POST client

Hello all i am trying to capture the json "post" data from the client and send it to other client i.e i am trying to get the data of the client who hit my url and i handle this data and send it to the actual url.For this i have created an internal post client where i handle the data and send to my actual url.
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String a = book.getId();
String b = book.getName();
String c = book.getAuthor();
String d = book.getPrice();
System.out.println(a + b + c + d);
byte[] out = "{\"id\":\"root\",\"name\":\"password\",\"price\":\"root\",\"author\":\"password\"}"
.getBytes();
int length = out.length;
conn.setFixedLengthStreamingMode(length);
conn.setRequestProperty("Content-Type",
"application/json; charset=UTF-8");
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(out);
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((output = br.readLine()) != null) {
response = output;
}
// return parseJSON(response);
return response;
I want to place my values of the strings a,b,c,d with the root,password,root,password respectively.
But when i try to place it i get the error insert missing quote.
Please help me regarding this
Thank you
Moving Comment to Answer as it worked for OP.
you can convert string to byte array as below:
byte[] request = new String("{\"id\":\"" + a + "\",\"name\":\"" +b+"\",\"price\":\"" + c+" \",\"author\":\"" + d+ "\"}").getBytes()

Send HTTP Post Payload with Java

I'm trying to connect to the grooveshark API, this is the http request
POST URL
http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77
POST payload
{"method":'addUserFavoriteSong",'parameters":{"songID":30547543},"header":
{"wsKey":'key","sessionID":'df8fec35811a6b240808563d9f72fa2'}}
My question is how can I send this request via Java?
Basically, you can do it with the standard Java API. Check out URL, URLConnection, and maybe HttpURLConnection. They are in package java.net.
As to the API specific signature, try sStringToHMACMD5 found in here.
And remember to CHANGE YOUR API KEY, this is very IMPORTANT, since everyone knows it know.
String payload = "{\"method\": \"addUserFavoriteSong\", ....}";
String key = ""; // Your api key.
String sig = sStringToHMACMD5(payload, key);
URL url = new URL("http://api.grooveshark.com/ws3.php?sig=" + sig);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStream os = connection.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
pw.write(payload);
pw.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
String response = sb.toString();
You could look into the Commons HttpClient package.
It is fairly straight forward to create POST's, specifically you could copy the code found here: http://hc.apache.org/httpclient-3.x/methods/post.html:
PostMethod post = new PostMethod( "http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77" );
NameValuePair[] data = {
new NameValuePair( "method", "addUserFavoriteSong..." ),
...
};
post.setRequestBody(data);
InputStream in = post.getResponseBodyAsStream();
...
Cheers,

Categories