Stone
Stone

Reputation: 43

How to use curl in Java

I've found there are several discussions about this topic, but what confuses me is another question. You see, the Object URL is used to get data from certain page. But how to write the URL when the page requires authorities?

The API suggests the curl code curl -i -X GET --header 'X-Auth-code:<your_code>' to be used, but how?

Upvotes: 0

Views: 3279

Answers (3)

Stone
Stone

Reputation: 43

This is the final solution: the key is the setRequestProperty() method

     try {
        String url = "http://121.41.106.89:8010/";

        URL readUrl = new URL(url);
        URLConnection connection = readUrl.openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("X-Auth-Code", "75d07493b655591137dbc905ede428ce");
        connection.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String result = in.readLine();
        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    }

Upvotes: 1

Saman Salehi
Saman Salehi

Reputation: 1034

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

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

I think this reference may help you.

Upvotes: 0

mmuzahid
mmuzahid

Reputation: 2280

To run command in a Java program, you could use Process and Runtime.

Try something like bellow:

Process p = Runtime.getRuntime().exec("curl -i -X ");
InputStream is = p.getInputStream();

Upvotes: 2

Related Questions