curl for java,如何在Java中使用cURL

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值