How to use cURL in Java?

后端 未结 6 1962
孤街浪徒
孤街浪徒 2020-11-22 14:03

I am a newbie in java and wanted to use curl in java. What is my question is curl built-in in java or I have to install it from any 3rd party source to use with Java. If so,

6条回答
  •  情话喂你
    2020-11-22 14:50

    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:

    • How to use java.net.URLConnection to fire and handle HTTP requests?
    • What are the pros and cons of the leading Java HTML parsers?

提交回复
热议问题