将Curl转换为Java等效项

时间:2015-10-23 19:29:59

标签: java curl httpurlconnection

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

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

1 个答案:

答案 0 :(得分:2)

curl -d发送您指定的任何内容,而不以任何方式格式化。只需在OutputStream中发送字符串names[]=EndUser/...,而不将其包装在JSONObject中。写完字符串后别忘了打电话给wr.flush()。当然,在那之后,你需要得到InputStream并开始阅读它(我只提到它,因为它不在你的代码片段中)。