【发布时间】:2015-05-14 05:18:29
【问题描述】:
我有一个 API 的 URL,如果直接在 chrome 的高级 rest 客户端中运行,它可以正常工作。我希望这个 URL 从我自己的 REST API 代码中触发,该代码应该在高级休息客户端中运行它并将结果存储在变量中。 我该怎么做?
【问题讨论】:
-
为什么需要它在高级REST客户端中运行?
标签: java rest google-chrome rest-client
我有一个 API 的 URL,如果直接在 chrome 的高级 rest 客户端中运行,它可以正常工作。我希望这个 URL 从我自己的 REST API 代码中触发,该代码应该在高级休息客户端中运行它并将结果存储在变量中。 我该怎么做?
【问题讨论】:
标签: java rest google-chrome rest-client
使用 Apache HttpClient 库 https://hc.apache.org/ 或其他一些第三方开源库来轻松编码。 如果您使用的是 apache httpClient lib,请 google 获取示例代码。小例子就在这里。
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet('http://site/MyrestUrl');
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = '';
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
return (rd);
如果使用第三方 jars 有任何限制,你也可以使用普通 java。
HttpURLConnection conn = null;
try {
URL url = new URL("http://site/MyRestURL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", ""); // add your content mime type
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
【讨论】:
在普通的java中,试试这样。我的建议请尝试使用好的开源 rest/http 客户端。网上有很多例子。
String httpsUrl = "https://www.google.com/";
URL url;
try {
url = new URL(httpsUrl);
HttpsURLConnection con = HttpsURLConnection)url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
【讨论】: