简体   繁体   中英

Invoking curl commands from Java

curl -k -XPOST 'https://localhost:9200/myweb/myrep/**input_string**/_update'  -d '{"doc":{"status":"Disconnected"}}'

Invoke above for a list of input_string from a XML file

Option 1: Write a bash script to accomplish above and then call this script from Java code

Option 2: RunTime.exec() to call curl command in a for loop like this : curl command in java

Is there any other better way?

This will be one of the important steps in my overall Java program which is doing various other things. That's the reason I am looking for ways to integrate this well with Java code rather than providing an option to run above as separate CLI script.

Here's implementation of POST and GET via HTTPURLConnection.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class PostGET {
    public static void main(String[] args) throws UnsupportedEncodingException {
        Map<String, String> headerMap = new HashMap<String, String>();
        String bodyStr = "{\"doc\":{\"status\":\"Disconnected\"}}";
        InputStream body = new ByteArrayInputStream(bodyStr.getBytes("UTF-8"));

        System.out.println("Sending POST");
        post("http://127.0.0.1:3000", headerMap, body);

        System.out.println("");

        System.out.println("Sending GET");
        get("http://127.0.0.1:3000?test=hello", headerMap);
    }

    public static void post(String targetUrl, Map<String, String> headerMap,
            InputStream body) {
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) new URL(targetUrl).openConnection();
            http.setRequestMethod("POST");
            http.setDoOutput(true);
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                http.setRequestProperty(header.getKey(), header.getValue());
            }

            OutputStream out = http.getOutputStream();
            out.write(readInput(body));
            out.close();

            InputStream in = http.getInputStream();
            String response = new String(readInput(in), "UTF-8");

            System.out.println("Response code: " + http.getResponseCode());
            System.out.println("Response headers : " + http.getHeaderFields());
            System.out.println("response from server: " + response);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void get(String targetUrl, Map<String, String> headerMap) {
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) new URL(targetUrl).openConnection();
            http.setRequestMethod("GET");

            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                http.setRequestProperty(header.getKey(), header.getValue());
            }

            InputStream in = http.getInputStream();
            String response = new String(readInput(in), "UTF-8");

            System.out.println("Response code: " + http.getResponseCode());
            System.out.println("Response headers : " + http.getHeaderFields());
            System.out.println("response from server: " + response);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static byte[] readInput(InputStream in) {
        ByteArrayOutputStream bais = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readLen = -1;
        try {
            while ((readLen = in.read(buffer)) != -1) {
                bais.write(buffer, 0, readLen);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bais.toByteArray();
    }
}

Below is a Nodejs Server to test this with

http = require('http');
server = http.createServer( function(req, res) {
    if (req.method == 'POST') {
        console.log("POST");
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log("Partial body: " + body);
        });
        req.on('end', function () {
            console.log("Body: " + body);
        });
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('post received');
    } else if(req.method === 'GET') {
        console.log("GET");
        var params = req.url.split('?');
        params = params.length > 1 ?  params[1] : "";
        console.log('params : ' + params);

        var html = '<html><body><h1>' + params+ '</h1></body>';
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(html);
    }

});

port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);

Java Client Output

Sending POST
Response code: 200
Response headers : {Transfer-Encoding=[chunked], null=[HTTP/1.1 200 OK], Connection=[keep-alive], Date=[Thu, 31 Dec 2015 19:40:05 GMT], Content-Type=[text/html]}
response from server: post received

Sending GET
Response code: 200
Response headers : {Transfer-Encoding=[chunked], null=[HTTP/1.1 200 OK], Connection=[keep-alive], Date=[Thu, 31 Dec 2015 19:40:05 GMT], Content-Type=[text/html]}
response from server: <html><body><h1>test=hello</h1></body>

Node Server Output

Listening at http://127.0.0.1:3000
POST
Partial body: {"doc":{"status":"Disconnected"}}
Body: {"doc":{"status":"Disconnected"}}
GET
params : test=hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM