将Curl转换为Java等效项

问题描述

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

解决方法

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 httpclient?

我尝试了几种不同的解决方案,但到目前为止没有任何效果,我可以找到的大多数示例都使用了已贬值的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();
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...