gpt4 book ai didi

java - 如何将 cURL 放入 Java

转载 作者:可可西里 更新时间:2023-11-01 17:06:05 24 4
gpt4 key购买 nike

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

我需要通过 HTTP/Curl 将文件“/home/myNewFile.txt”上传到 Http 服务器(在本例中是 Artifactory 或)


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

提前致谢!

最佳答案

首先,将您的 URLConnection 转换为 HttpURLConnection。

总而言之,代码如下所示:

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 放入 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com