How to convert the below curl command in Java using HttpURLConnection? - java

How to convert the below curl command to Java using HttpURLConnection?
curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "https://example.com:8081/rest/api/2/issue/QA-31"

How to set headers:
HttpURLConnection myCon = (HttpURLConnection) new URL("https://example.com:8081/rest/api/2/issue/QA-31").openConnection();
myCon.setRequestMethod("GET");
myCon.setRequestProperty("Content-Type","application/json");
myCon.setRequestProperty("Authorization", "Basic ZnJlZDpmcmVk");
After that you can read URL content in two ways
a. you can get InputStream from Connection as
InputStream inStream = myCon.getInputStream();
and read it as you want directly or with some reader etc.
b. by getting Content as
Object content = myCon.getContent();
For details read Java Docs for those methods it is very well documented.
BTW: keep in mind you have an SSL connection then you have to have remote server certificate in your java Key Store.

Related

how to make requests to an api

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)

How to set Request Body parameter in rest api

I have api using curl
curl -X PUT "http://localhost:8080/kie-server/services/rest/server/containers/containerid/tasks/210/expiration" -H "accept: application/json" -H "content-type: application/json" -d "{ \"java.util.Date\" : 1540025263987}"
Now I want to call this api using java code :
I am using javax.ws.rs.PUT class for api calling and HttpConnection class.
I have set the requestMethod(POST) and request property.
This is url i am using :
http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration
url = new URL( http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration);
conn.setRequestMethod(PUT);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
I want to pass this parameter to api but not sure which method to use ?
{java.util.Date:1534343434"};
This parameter is passed in body.
Can anyone suggest how do I pass this parameter in java rest api ??

Convert Python request with image to cURL

I found this example of a API request. Unfortunately I didn't find any other example how to upload an image to the API.
As I'm not familiar with Python I'm trying to understand how to do the same in a cURL command.
import requests
auth_headers = {
'app_id': 'your_app_id',
'app_key': 'your_app_key'
}
url = 'https://XXXXXXX'
files = {
'source': open('media/test.jpg')
}
data = {
'timeout': 60
}
response = requests.post(url, files=files, data=data, headers=auth_headers)
I tried to convert it by trying out a cURL to python converter, but I don't know how to build it with the files.
In the end I want to do the request in JAVA, but I think if I would know the request in cURL I can figure it out.
Hope anyone can help me with that.
This will do it:
#!/bin/bash
args=(
-H 'app_id: your_app_id'
-H 'app_key: your_app_key'
-F 'source=#/path/to/file'
-F 'timeout=60'
'http://httpbin.org/post'
)
curl "${args[#]}"
or, as a one-liner:
curl -H 'app_id: your_app_id' -H 'app_key: your_app_key' -F 'source=#/path/to/file' -F 'timeout=60' 'http://httpbin.org/post'
Use -H to specify header fields (repeat for every field) and -F to specify form fields - either as key=value pairs, or filename=#path pairs. When -F is used, POST method is the default, and Content-Type is multipart/form-data (but that too can be overridden).

How to cURL Put in Java

Looking for an easy way to replicate the following Linux cUrl command in java:
I need to upload the file "/home/myNewFile.txt" via HTTP / Curl to a Http server (which in this case is artifact or)
curl -u myUser:myP455w0rd! -X PUT "http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt" -T /home/myNewFile.txt
Thanks in advance!
First, cast your URLConnection to an HttpURLConnection.
For curl’s -X option, use setRequestMethod.
For curl’s -T option, use setDoOutput(true), getOutputStream(), and Files.copy.
For curl’s -u option, set the Authorization request header to "Basic " (including the space) followed by the base 64 encoded form of user + ":" + password. This is the Basic Authentication Scheme described in the RFC 2616: HTTP 1.1 specification and RFC 2617: HTTP Authentication.
In summary, the code would look like this:
URL url = new URL("http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String auth = user + ":" + password;
conn.setRequestProperty("Authorization", "Basic " +
Base64.getEncoder().encodeToString(
auth.getBytes(StandardCharsets.UTF_8)));
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
try (OutputStream out = conn.getOutputStream()) {
Files.copy(Paths.get("/home/myNewFile.txt"), out));
}
I am not advocating that this is the correct way to do things, but you could execute the command line statement as is directly from your java file.
Here is a snippet of code from a program I wrote that executes a php script (using a linux commandline statement) from within a java program I wrote.
public void executeCommand(String command)
{
if(command.equals("send_SMS"))
{
try
{
//execute PHP script that calls Twilio.com to sent SMS text message.
Process process = Runtime.getRuntime().exec("php send-sms.php\n");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This worked for me.
Check out the API for the Process and Runtime classes here:
https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
and
https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

How to send -u data of Curl in Rest client

I have a Curl request like:
curl -u "key:value" -H "headers" https://example.com
So, when I try to create a Rest client using this curl request in Java I am confused where to send the -u data in my request. Do we need to send it in Header or as URL parameter. Can somebody help me and tell me how can I send this -u in my Java code?
This is the code I am using:
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Headers", "Value");
***conn.setRequestProperty("u", "key:Value");***
The header Authorization: Basic base64encoded(user:pass) works for this question.

Categories

Resources