如何在Java中从第三方Rest终端下载文件

huangapple go评论75阅读模式
英文:

How to download files from a third party Rest end point in Java

问题

我想在Java中从第三方REST端点下载文件

谷歌提供了一个样本CURL并且按预期工作但我想在Java中进行设计
我尝试在谷歌上搜索但没有得到帮助

请求方法是GET”,并且是一个多部分HTTP请求

```java
curl -L -O -k -u '用户名:密码' -X GET http://localhost:8080/secure/attachment/1461863/fileName.txt

任何样本代码或链接都会很有帮助。

谢谢


<details>
<summary>英文:</summary>

I want to download a file from a third party rest end-point in java

Sample CURL available from google and it is working as expected but I want to design it in java.
I tried googling it but could not get help.

Request method is &quot;GET&quot; and a multipart HTTP request

curl -L -O -k -u 'username:password' -X GET http://localhost:8080/secure/attachment/1461863/fileName.txt


Any sample code or link will do good.

Thanks

</details>


# 答案1
**得分**: 0

如果您不想使用除了jdk以外的额外依赖,可以使用类似以下的方法:

```java
URL url = new URL("http://localhost:8080/secure/attachment/1461863/fileName.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
英文:

If you don't want to use additional dependecies other than jdk, you can use something like this:

URL url = new URL(&quot;http://localhost:8080/secure/attachment/1461863/fileName.txt&quot;);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setRequestMethod(&quot;GET&quot;);

	if (conn.getResponseCode() != 200) {
		throw new RuntimeException(&quot;Failed : HTTP error code : &quot;
				+ conn.getResponseCode());
	}

huangapple
  • 本文由 发表于 2020年5月4日 15:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/61587431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定