How to cURL Put in Java

走远了吗. 提交于 2019-12-24 07:39:59

问题


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!


回答1:


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));
}



回答2:


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



来源:https://stackoverflow.com/questions/42259075/how-to-curl-put-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!