如何cURL放入Java

时间:2017-02-15 20:10:58

标签: java linux http curl artifactory

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

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

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

提前致谢!

2 个答案:

答案 0 :(得分:2)

首先,将URLConnection转换为HttpURLConnection。

  • 对于curl的-X选项,请使用setRequestMethod
  • 对于curl的-T选项,请使用setDoOutput(true)getOutputStream()Files.copy
  • 对于curl -u选项,请将Authorization request header设置为"Basic "(包括空格),然后设置user + ":" + password 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)); } 形式的set :application, 'APP_NAME' set :repo_url, 'git@bitbucket.org:USERNAME/APP_NAME.git' set :user, "deploy" set "stages", %w(production staging) set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system') namespace :deploy do after :restart, :clear_cache do on roles(:web), in: :groups, limit: 3, wait: 10 do # Here we can do anything such as: # within release_path do # execute :rake, 'cache:clear' # end end end end 。这是base 64 encoded规范和RFC 2616: HTTP 1.1中描述的基本身份验证方案。

总之,代码如下所示:

role :app, %w{deploy@ADDRESS}
role :web, %w{deploy@ADDRESS}
role :db, %w{deploy@ADDRESS}, :primary => true
set :branch, "master"
set :rails_env, "staging"
set :deploy_to, "var/www/APP_NAME_production"

答案 1 :(得分:0)

我并不是说这是正确的做事方式,但您可以直接从java文件中执行命令行语句。

以下是我编写的程序代码片段,该程序在我编写的java程序中执行php脚本(使用linux命令行语句)。

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

这对我有用。

在此处查看Process和Runtime类的API:

https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html