How to replicate curl command using java? - 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

Related

Pass json object by navigator instead of java

I have a java application with this code :
URL url = new URL("http://myurl/");
HttURLConnection connection = (HttURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutplut(true);
connection.setRequestProperty("Content-Type", "application/json");
BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
buffer.write("{\"foo:\"0}");
buffer.flush();
I just want to do the samething in my navigatour URL bar.
Edit
I found a tool to modifier headers. Here a screenshoot of the dev tool when I load my page.
Now where did I put my Json object?
If you need to send JSON data to your URL your code should be like this,
URL url = new URL("http://myurl/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
String input = "{\"foo\":\"bar\"}";
OutputStream ous = con.getOutputStream();
ous.write(input.getBytes());
ous.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}else
{
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
}
con.disconnect();
If you need GET Method then you can place this,
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
If you need to send Request Body with the URL you can use CURL. And also you can use POSTMAN. By using this you can send requests and receive the response.
CURL will be like this,
curl -v -H "Content-Type: application/json" -X POST \
-d '{\"foo\":\"bar\"}' http://myurl/
You can use Firefox to perform what you need, Read the 2nd answer.

JSON POST Data via HttpURLConnection

I am trying to make a request to my RESTful API using Android and HttpURLConnection. The data must be sent in the JSON format via POST data.
Here is my code:
JSONObject check_request = new JSONObject();
check_request.put("username", username);
JSONObject request = BuildRequest(check_request, "username_check", false);
Log.i("DEBUG", request.toString());
// DEBUG OUTPUT: {"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}
URL request_url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection)request_url.openConnection();
connection.setRequestProperty("User-Agent", "TheGameApp");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream os = connection.getOutputStream();
os.write(request.toString().getBytes("UTF-8"));
os.flush();
InputStream in = new BufferedInputStream(connection.getInputStream());
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
String str;
while ((str = br.readLine()) != null)
{
result += str;
}
Log.i("DEBUG", result);
//JSONObject result_json = new JSONObject(result);
os.close();
in.close();
connection.disconnect();
You can see the Debug output as a Comment. The Problem is that the API does not receive any POST data. I have used PHPs var_dump to dump $_POST and $_REQUEST which both are empty arrays.
What am I missing here?
As the question popped up if the API work. This cURL command works fine with the correct result (it is the same JSON data as the debugger printed):
curl -d '{"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}' -H "Content-Type: application/json" -X POST http://localhost/v1/api.php
Just for the sake of completeness: The example above is working. The solution to the problem was pa part in PHP on the server side, where I checked the content type and used strpos to search for application/json in $_SERVER['CONTENT-TYPE'] and switched the needle and haystack (thus searching for application/json; charset=UTF8 in the string application/json instead of the other way around).

Convert cURL to Java for SOAP Call

Im implementing a SOAP web service and it is working with a cURL call. I implemented following this tutorial. The service is working with the following command:
curl --header "content-type: text/xml" -d #request.xml http://localhost:8080/ws
But of course this action has to be free from command prompt and be able to be called whenever necessary, so I want to relate this service to an action when a method is called for example.
So far I found from internet
String url = "http://localhost:8080/ws";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Content-Type", "text/xml");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
I assume it should be a POST method but how do I add the "request.xml" and "--header"? What command will finalize the cURL call? Or am I doing this totally wrong and the long way, is there an easier way?
PS: I already have a web service running and Im using Eclipse Oxygen.
Add below lines to your code at the end, it will do the JOB.
OutputStream wr = new DataOutputStream(conn.getOutputStream());
BufferedReader br = new BufferedReader(new FileReader(new File("request.xml")));
//reading file and writing to URL
System.out.println("Request:-");
String st;
while ((st = br.readLine()) != null) {
System.out.print(st);
wr.write(st.getBytes());
}
//Flush&close the writing to URL.
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
// printing result from response
System.out.println("Response:-" + response.toString());
While HttpURLConnection can be used for this purpose, SOAPConnection was designed for situations where there is not a WSDL.
The code below is much simpler:
SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage msg =
MessageFactory.newInstance()
.createMessage(null, Files.newInputStream(Paths.get("request.xml")));
SOAPMessage resp = conn.call(msg, "http://localhost:8080/ws");
resp.writeTo(System.out);

How i can get connected with qc 12 with rest api

Can u please help me to understand with simple piece of java code to get connect wth qc 12 using rest api.
I gone thorough the rest api documentation but am not clear with how to start with.but it will be helpful if people can show me a simple java code for authentication(login,logout or getting defect details) using rest api. Also want to know do i need to include any jars in my build path.
Thanks a lot friends.
I don't quite get what you're asking, but if you want to connect to a REST API, there are several ways... I usually use HttpURLConnection, here's an example of a get:
public String getProfile(String URL) throws IOException {
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpURLConnection con = (HttpURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
//Add the request headers.
con.setRequestProperty("header", headerValue);
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save the response.
response.append(inputLine + '\n');
}
br.close();
return response.toString();
}

How do I get the results of a second line of a HTTP POST into a string?

I am making an android app that retrieves information via HTTP POST. The problem is that while I can retrieve the relevant data, it doesn't want to output on different lines. For example, I have the following simple php script:
<?php
if(!isset($_POST["test"])) $test="no test\n";
else $test=$_POST["test"];
echo "hello1 \r\n";
echo "hello2";
?>
On a normal HTTP Post, it would responsd "hello1" on one line, and "hello2" on the next line. However, when I receive it in Android, it comes out as "hello1 hello2".
Preferably I would want to get the second line into another string rather than on the same line, but I'm not sure how to do this on Android.
The code for the Android app is:
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
String urlParameters = ("test=");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString()); //print result
On your while, extract the second line like this
int line = 0;
while ((inputLine = in.readLine()) != null) {
line++;
if(line==2)
response.append(inputLine);
}

Categories