将 Curl 转换为 Java 等价物

Convert Curl to Java equivalent

我是第一次使用 New Relic REST API,我有一个 curl 命令:

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' 

我想在 java servlet 中发送此命令,并从准备好解析的响应中获取 JSON 对象,最佳解决方案是什么?

HttpURLConnection?

Apache http客户端?

我尝试了几种不同的解决方案,但到目前为止没有任何效果,我能找到的大多数示例都在使用已折旧的 DefaultHttpClient

这是我的其中一项尝试的示例:

 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());

编辑

我稍微修改了代码,现在可以使用了,谢谢。

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();
        }

curl -d 发送您指定的任何内容,而不以任何方式对其进行格式化。只需在 OutputStream 中发送字符串 names[]=EndUser/...,而不将其包装在 JSONObject 中。不要忘记在写入字符串后调用 wr.flush() 。当然,在那之后,您需要获取 InputStream 并开始阅读它(我只提到它是因为它不在您的代码段中)。