【发布时间】:2015-10-23 19:29:59
【问题描述】:
我是第一次使用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();
}
【问题讨论】:
-
我建议使用像 Apache HttpComponent 或 Unirest 这样的库来大大简化这个过程。
-
Apache HttpComponent 有什么优势?
-
这是一个更易于编码、理解和维护的 API。 Unirest 建立在 Http 组件之上,通过 http 连接更加容易。
-
酷,谢谢,我想我会修改我的代码来使用它。
标签: java curl httpurlconnection