How to cURL Put in Java - 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

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 download files from a third party Rest end point in Java [duplicate]

This question already has answers here:
How do I save a file downloaded with HttpClient into a specific folder
(7 answers)
Closed 2 years ago.
I want to download a file from a third party rest end-point in java
Sample CURL available from google and it is working as expected but I want to design it in java.
I tried googling it but could not get help.
Request method is "GET" and a multipart HTTP request
curl -L -O -k -u 'username:password' -X GET http://localhost:8080/secure/attachment/1461863/fileName.txt
Any sample code or link will do good.
Thanks
If you don't want to use additional dependecies other than jdk, you can use something like this:
URL url = new URL("http://localhost:8080/secure/attachment/1461863/fileName.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

Network is unreachable during http request in Java, but curling domain works

So I am trying to make a HTTP request to microsoft.com on a spring app.
I am running the jar with the following command on my red hat 7 linux server.
java -Dhttp.proxyHost=http://http.proxy.mycompany.com -Dhttp.proxyPort=8000 \
-Dhttps.proxyHost=http://http.proxy.mycompany.com -Dhttps.proxyPort=8000 \
-D -jar Server-0.0.1-SNAPSHOT.jar
I have echod the proxy values on the linux server and they are identical.
This is how I am making a request in Java, the print statements were to confirm the proxy was being set correctly (it was):
System.out.println(System.getProperty("http.proxyHost"));
System.out.println(System.getProperty("https.proxyHost"));
System.out.println(System.getProperty("http.proxyPort"));
System.out.println(System.getProperty("https.proxyPort"));
try {
URL url = new URL("https://microsoft.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
System.out.println(con.getResponseMessage());
int status = con.getResponseCode();
System.out.println(status);
return status;
}catch(Exception e) {
e.printStackTrace();
}
return 0;
This command shows me my firewall setup
sudo firewall-cmd --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0
sources:
services: ssh bigfix
ports: 80/tcp 8080/tcp 8080/udp 8443/tcp 443/tcp 8000/tcp
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks: destination-unreachable echo-reply parameter-problem redirect
router-advertisement router-solicitation source-quench time-exceeded
rich rules:
The error is java.net.SocketException: Network is unreachable.
Has anyone got any ideas on how to troubleshoot what is going wrong on my server?

How do I use curl in Java to make a call to a url?

I am using the following CURL command to save the response in .pdf format:
curl -d "#name_of_xmlFile.xml" -X POST http:url/ -o name_of_response_pdfFile.pdf
how to make the call and save the response generated pdf file in a specific folder using java.
Welcome to stack overflow !
The problem here is that curl is a Linux command. Because Java is intended to be written once and run everywhere (on any machine), then java cannot directly use commands like curl, which do not exist by default on every operating system.
Therefore you need to include additional functionality from elsewhere.
Personally I like to use Unirest which is a nice simple lightweight framework to aid with using Rest in Java.
Good luck !
You can also perform a post in Java without using curl (not sure whether using curl is a MUST have requirement)
taken from this article:
private void doPost() throws Exception {
String url = "http:url/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
// could ewually save to file rather than to stdout.
}
For sending the body, you may try this.
If using curl is a hard requirement, you may use Runtime.getRuntime().exec(command); as shown here, but be aware that this isn't necessarily portable (e.g. if curl is not installed) and could be unsafe if the commands being run aren't in some way validated to prevent bad actors running arbitrary commands etc...

Http request using sockets

I have to send some command using HTTP request to some applications that have embedded http server.I'm using sockets,so far I did this but I'm a little lost:
URI uri = URI.create(rawData);
try {
String host = uri.getHost();
String path = uri.getRawPath( );
if (path == null || path.length( ) == 0) {
path = "/";
}
String protocol = uri.getScheme( );
int port = uri.getPort( );
if (port == -1) {
if (protocol.equals("http")) {
port = 80; // http port
}
else if (protocol.equals("https")) {
port = 443; // https port
}
}
Socket socket = new Socket( host, port );
PrintWriter request = new PrintWriter( socket.getOutputStream() );
request.print( "GET " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
request.flush( );
Is this all I need to do?
An example of rawData is "http://somemessage".Is the protocol written correctly?
Thanks
Is this all I need to do?
Nope.
You need to process the response, and there is complexity in dealing with the various kinds of responses you could receive.
The way you are handling HTTPS is all wrong. You need to deal with SSL connection negotiation ... and if you try to do that using plain sockets you have a huge amount of coding to do.
An example of rawData is "http://somemessage"
What is a strange URL. The stuff after the "//" should be (or include) a resolvable hostname or IP address. If you tried to fetch a URL like that using a web browser, it would not work.
Is the protocol written correctly?
Certainly the URL is not written correctly. If you try to use that so-called URL with HttpURLConnection, or any the other client-side HTTP API (see below), IT WILL NOT WORK!!!
A typical well-formed URL (in this case, with an explicit port number) looks like this:
http://example.com:8080/path/to/resource
You can also express URIs in relative form; e.g.
http:/path/to/resource
or
http:relpath/to/resource
or even
resource
but those two forms need to be turned into absolute (URL) form before they can be used by a client library.
But frankly, this is the wrong way to go about things. There are existing implementations of the client-side HTTP / HTTPS stack in the Java SE libraries, and also in the Apache HTTP libraries. Attempting to reimplement them is a waste of time.
You can use higher-level JDK APIs instead of the lower-level Socket API for your requirement. Please refer to the following links -
http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html
http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/HttpsURLConnection.html
Below is a sample snippet with HttpURLConnection API -
String urlString = "http://myhost/mywebapp/myresource";
URL url= new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(timeout);
conn.setRequestMethod("GET");
conn.getResponseCode();

Categories

Resources