如何在Java中使用cURL [英] How to cURL Put in Java

查看:463
本文介绍了如何在Java中使用cURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种简单的方法来在Java中复制以下Linux cUrl命令:

Looking for an easy way to replicate the following Linux cUrl command in java:

我需要通过HTTP/Curl将文件"/home/myNewFile.txt"上传到Http服务器(在这种情况下为人工制品或)

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

curl -u myUser:myP455w0rd! -X PUT "http://localhost:8081/artifactory/my-repository/my/new/artifact/directory/file.txt" -T /home/myNewFile.txt

提前谢谢!

推荐答案

首先,将URLConnection强制转换为HttpURLConnection.

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

这篇关于如何在Java中使用cURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆