Convert Curl to Java equivalent

2020-03-25 06:46发布

问题:

I'm working with New Relic REST API for the first time, I have a curl command:

curl -X GET 'https://api.newrelic.com/v2/applications/appid/metrics/data.json' \
     -H 'X-Api-Key:myApiKey' -i \
     -d 'names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp' 

I want to send this command in a java servlet and get a JSON object from the response ready for parsing, What is the best solution?

HttpURLConnection?

Apache httpclient?

I've tried a few different solutions, but nothing has worked so far and most examples I could find are using the depreciated DefaultHttpClient

Here is an example of one of my attempts:

 String url = "https://api.newrelic.com/v2/applications.json";
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("X-Api-Key", "myApiKey");
        conn.setRequestMethod("GET");
        JSONObject names =new JSONObject();

        try {
            names.put("names[]=", "EndUser/WebTransaction/WebTransaction/JSP/index.jsp");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OutputStreamWriter wr= new OutputStreamWriter(conn.getOutputStream());
        wr.write(names.toString());

Edit

I've modified the code a bit, it's working now thanks.

String names = "names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp";
String url = "https://api.newrelic.com/v2/applications/myAppId/metrics/data.json";
String line;

try (PrintWriter writer = response.getWriter()) {

            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("X-Api-Key", "myApiKey");
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(names);
            wr.flush();


            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                writer.println(HTML_START + "<h2> NewRelic JSON Response:</h2><h3>" + line + "</h3>" + HTML_END);
            }
            wr.close();
            reader.close();
        }catch(MalformedURLException e){

            e.printStackTrace();
        }

回答1:

curl -d sends whatever you specify without formatting it in any way. Just send the string names[]=EndUser/... in the OutputStream, without wrapping it in a JSONObject. Don't forget to call wr.flush() after writing the string. And of course, after that, you need to get the InputStream and start reading from it (I only mention this because it's not in your snippet).