击中Java Web服务:curl或URLConnection [英] Hitting Java web service: curl or URLConnection

查看:95
本文介绍了击中Java Web服务:curl或URLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java服务器,该服务器在以下URL上公开RESTful API:

I am using a Java server that exposes a RESTful API on the following URL:

http://localhost:8080/my-server/

文档建议使用curl提交简单的PUT请求(文件上传),并强烈建议用户使用示例中提供的完全相同的参数.所有示例如下所示:

The docs recommend using curl for submitting simple PUT requests (file uploads), and strongly recommend users to use the exact same arguments as provided in the examples. All of the examples look like this:

curl -X PUT -f -u admin:password --data-binary @/absolute/path/file/to/upload/file.ext "http://localhost:8080/my-server/file.ext"

此服务器无法使用FTP或任何其他常规传输协议.

This server will not work with FTP or any other normal transfer protocol.

我在SO上找到了这个问题,建议回答者使用java.net.URL及其伴侣java.net.URLConnection,而不是尝试使用curl/libcurl.

I found this question on SO where the answer-er recommended using java.net.URL and its companion java.net.URLConnection instead of trying to work with curl/libcurl.

我以前从未运行过curl命令,所以我问同时知道curl和Java的任何人是否可以使用URL/URLConnection(或任何其他Java框架)代替curl来解决我的特定问题.如果没有,那么我将不得不编写一个从本地命令行/终端执行命令的组件,然后在该组件内部执行上面的curl命令,感觉很丑/讨厌.

I've never even ran a curl command before, so I am asking anyone who knows both curl and Java if URL/URLConnection (or any other Java framework) can be used instead of curl for my specific problem here. If not, then I will have to write a component that executes commands from the local command-line/terminal, and then execute the above curl command inside that component, and that just feels ugly/nasty.

如果我可以在Java网络API中完成相同的操作,那么我宁愿那样做.

If I can accomplish the same thing in a Java network API, I would prefer to do it that way.

而且,如果可以用Java完成,我将如何使用URL/URLConnection设置与我提供的示例相同的 exact 命令命令?具体来说:

And, if it can be done in Java, how would I use URL/URLConnection to set up the exact same command arguments as the example I provided? Specifically:

  • -X
  • PUT
  • -f
  • -u admin:password
  • --data-binary
  • -@absolute/path/...
  • -X
  • PUT
  • -f
  • -u admin:password
  • --data-binary
  • -@absolute/path/...

在此先感谢您的任何见解或向正确的方向前进!

Thanks in advance for any insight here or nudges in the right direction!

推荐答案

我相信使用Java和:

I believe this is more-or-less equivalent using Java and httpclient-4.x:

try {
    Credentials credentials = new UsernamePasswordCredentials("admin", "password");  //-u admin:password
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    HttpPut put = new HttpPut("http://localhost:8080/my-server/file.ext");  //-X PUT
    put.setEntity(new FileEntity(new File("/absolute/path/file/to/upload/file.ext"), "image/png"));  //@ - absolute path
    httpClient.execute(put);
} catch(Exception e) {
    //-f, fail silently
}

这篇关于击中Java Web服务:curl或URLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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