Jersey REST服务调用外部API报500错误,求排查解决
问题分析与解决方案
咱们一步步拆解你遇到的问题,先从最直接的错误说起:
1. 方法名大小写不匹配(直接触发500错误)
你在TestClass里定义的方法是getData()(大写D),但在Jersey的employee类里调用的却是getdata()(小写d)——Java是严格区分大小写的语言,这会导致编译错误,运行时JVM找不到对应方法,直接引发Servlet初始化失败(也就是你看到的500错误)。先把这个最基础的错误修正:
@Path("/employees") public class employee { @GET @Path("/getEmployees") public String createNewMassage() { // 修正方法名大小写 return TestClass.getData(); } }
2. getData()方法的返回值逻辑错误
你的getData()里,output变量在while循环中每次都会被br.readLine()覆盖,最后返回的只是响应的最后一行内容,而不是完整的JSON串;如果响应为空还会返回null,这会导致Jersey返回异常或空内容。需要用StringBuilder拼接所有响应行:
public class TestClass { public static String getData() { StringBuilder fullResponse = new StringBuilder(); try { URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/application.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // GET请求没有请求体,不需要设置Content-Type // conn.setRequestProperty("Content-Type", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("请求失败:HTTP状态码 " + conn.getResponseCode()); } InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String line; while ((line = br.readLine()) != null) { fullResponse.append(line); } // 确保资源被正确关闭 br.close(); in.close(); conn.disconnect(); } catch (Exception e) { // 不要只打印异常,抛出异常让Jersey感知到错误 throw new RuntimeException("获取USGS数据失败", e); } return fullResponse.toString(); } }
3. 资源管理与异常处理优化
为了避免资源泄漏,建议用Java 7+的try-with-resources语法自动关闭流和连接,同时优化异常处理让Jersey能返回更友好的错误响应:
public static String getData() { StringBuilder fullResponse = new StringBuilder(); // try-with-resources自动关闭实现AutoCloseable的资源 try (URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/application.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in)) { conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("请求失败:HTTP状态码 " + conn.getResponseCode()); } String line; while ((line = br.readLine()) != null) { fullResponse.append(line); } } catch (Exception e) { throw new RuntimeException("获取USGS数据失败", e); } return fullResponse.toString(); }
4. Jersey资源方法的优化(可选)
如果想让客户端明确知道返回的是JSON,可以返回Response对象并设置正确的响应头:
@Path("/employees") public class Employee { // 类名建议大写,符合Java命名规范 @GET @Path("/getEmployees") public Response createNewMassage() { try { String jsonData = TestClass.getData(); return Response.ok(jsonData, MediaType.APPLICATION_JSON).build(); } catch (RuntimeException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("数据获取错误:" + e.getMessage()) .build(); } } }
额外调试建议
下次遇到500错误,一定要查看服务器的日志(比如Tomcat的catalina.out),里面会有详细的错误堆栈信息,能帮你快速定位问题根源。
内容的提问来源于stack exchange,提问作者Asras
相关产品推荐
相关产品推荐

