如何用Servlet调用本地接口
时间: 2024-06-08 22:09:25 浏览: 43
要用Servlet调用本地接口,可以使用Java提供的URLConnection或HttpClient来实现。
以下是使用URLConnection调用本地接口的示例代码:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URL url = new URL("http://localhost:8080/your/local/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
```
这段代码发送一个GET请求到地址为"http://localhost:8080/your/local/api"的本地接口,并将返回的JSON数据打印到控制台上。可以根据需要修改请求方法、请求头和请求参数等。
阅读全文