如何在 Java 中使用 cURL?

我是一个新手在爪哇,并希望在爪哇使用 curl。我的问题是,cURL 是 Java 内置的,还是我必须从任何第三方源安装它才能与 Java 一起使用。如果是这样,如何在 java 中安装 curl。我已经在谷歌上搜索了很长时间,但是没有找到任何帮助。希望有人能帮我。

先谢谢你。

265419 次浏览

You can make use of java.net.URL and/or java.net.URLConnection.

URL url = new URL("https://stackoverflow.com");


try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}

Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.

By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".

See also:

Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.

Curl is a non-java program and must be provided outside your Java program.

You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)

The Runtime object allows you to execute external command line applications from Java and would therefore allow you to use cURL however as the other answers indicate there is probably a better way to do what you are trying to do. If all you want to do is download a file the URL object will work great.

Some people have already mentioned HttpURLConnection, URL and URLConnection. If you need all the control and extra features that the curl library provides you (and more), I'd recommend Apache's httpclient.

Use Runtime to call Curl. This code works for both Ubuntu and Windows.

String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String line;
String response;
while ((line = reader.readLine()) != null) {
response.append(line);
}

Paste your curl command into curlconverter.com/java/ and it'll convert it into Java code using java.net.URL and java.net.URLConnection.