JSP实现两国距离计算时OkHttpClient等类无法识别问题求助
解决JSP中OkHttpClient、JSON类无法识别的问题
问题场景
编写了一个调用Google Maps Distance Matrix API计算两地距离与通行耗时的JSP页面,但代码中的OkHttpClient、Request、Response、JSONObject、JSONArray类始终无法被识别,导入类声明后问题仍未解决。
具体解决步骤
1. 统一依赖版本并补全正确导入
代码中同时导入了旧版com.squareup.okhttp.OkHttpClient和新版okhttp3.OkHttpClient,会导致类冲突,需统一使用新版okhttp3包,并补全所有缺失的类导入:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ import okhttp3.OkHttpClient; %> <%@ import okhttp3.Request; %> <%@ import okhttp3.Response; %> <%@ import org.json.JSONObject; %> <%@ import org.json.JSONArray; %>
2. 确保依赖包已添加到项目
- Maven项目:在
pom.xml中添加以下依赖(使用最新稳定版):
<!-- OkHttp3 网络请求库 --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.12.0</version> </dependency> <!-- JSON 解析库 --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency>
- 非Maven项目:手动下载以下JAR包,放到项目的
WEB-INF/lib目录下:- okhttp-4.x.x.jar
- okio-3.x.x.jar(OkHttp依赖的IO工具包)
- json-2024xxxx.jar
3. 修正代码中的潜在问题
- 避免变量名与JSP内置对象冲突(将
request改为req); - 添加异常捕获,防止网络请求失败导致页面崩溃;
- 使用try-with-resources自动关闭响应资源,避免内存泄漏:
<% if (request.getMethod().equals("POST")) { String apiKey = "YOUR_API_KEY"; String origin = request.getParameter("origin").replaceAll("\\s", "+"); String destination = request.getParameter("destination").replaceAll("\\s", "+"); String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + origin + "&destinations=" + destination + "&units=metric&key=" + apiKey; OkHttpClient client = new OkHttpClient(); Request req = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(req).execute()) { if (!response.isSuccessful()) throw new IOException("请求失败:" + response); String jsonData = response.body().string(); JSONObject jsonObj = new JSONObject(jsonData); JSONArray rows = jsonObj.getJSONArray("rows"); JSONObject elements = rows.getJSONObject(0).getJSONArray("elements").getJSONObject(0); String distance = elements.getJSONObject("distance").getString("text"); String duration = elements.getJSONObject("duration").getString("text"); out.print("<p>两地距离:" + origin.replaceAll("\\+", " ") + " 到 " + destination.replaceAll("\\+", " ") + " 为 " + distance + ",预计耗时 " + duration + "</p>"); } catch (Exception e) { out.print("<p>错误信息:" + e.getMessage() + "</p>"); e.printStackTrace(); } } %>
4. 检查容器类加载配置
确保WEB-INF/lib目录下的JAR包能被Web容器(如Tomcat)正确加载,不要将依赖包放到容器全局lib目录,避免版本冲突。
内容的提问来源于stack exchange,提问作者Karoui Fares
相关产品推荐
相关产品推荐

