繁体   English   中英

调用 spring-boot API 时的状态码 404,但不适用于 postman 或浏览器

[英]Status code 404 when calling spring-boot API, but not for postman or browser

我想对使用 Spring-Boot 构建的本地 REST 服务器进行 API 调用,该服务器正在与 Z685A5F7CC705B47EF086FZ6 交互。 我已经检查了一些我发现的关于这个主题的帖子,但我的问题似乎有点不同。

以下是一些相关的代码片段:

protected static CoreEntity[] sendGET(CoreEntity[] resultList, String path) throws IOException {
    path = String.join("%20", path.split(" "));
    return handleResponse(resultList, getConnection(path, "Get"));
}

private static HttpURLConnection getConnection(String path, String requestMethod) throws IOException {
    URL url = new URL(REQUEST_URL + path);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("accept", "application/json");
    connection.setConnectTimeout(50000);
    connection.setReadTimeout(50000);
    connection.setRequestMethod(requestMethod);
    initializeGSON();
    return connection;
}

private static CoreEntity[] handleResponse(CoreEntity[] resultList, HttpURLConnection connection) {
    try {
        final int status = connection.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) { // Success
            try (InputStreamReader reader = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(reader)) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
                reader.close();
                in.close();
                JSONArray jsonArray = getJSONAsArray(response.toString());
                resultList = (CoreEntity[]) Array.newInstance(resultList.getClass().getComponentType(), jsonArray.length());
                for (int i = 0; i < jsonArray.length(); i++)
                    resultList[i] = (CoreEntity) GSON.fromJson(jsonArray.get(i).toString(), resultList.getClass().getComponentType());
            } catch (IOException | JSONException e) { e.printStackTrace(); }
        } else {
            System.out.println("\nRequest failed with error code: " + status);
        }
        connection.disconnect();
        return resultList;
    } catch (ConnectException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

The response for http://www.google.com or any other homepage is successful with status code 200. But as soon as I call my API I get an error with status code 404. Strange is that everything works when I am using Postman或浏览器。 因此,当我通过 postman 向以下方法( http://localhost:8080/pets/3 )发出获取请求时,我可以看到打印输出并从 Z685A5F7CC75B4796F6C6E00Z38 获取数据,但不是上面的代码。 对于上面的代码,服务器端什么都没有发生,没有打印出来,没有异常,什么都没有。

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<T> getById(@PathVariable final long id) {
    System.out.println("TEST ===> " + id);
    T entity = getService().getById(id);
    return entity == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(entity);
}

似乎我的应用程序无法找到 API,但我已经验证 URL 是正确的,这就是为什么我不明白错误代码 404。

我还阅读了有关 package 可见性的信息,但我的结构如下所示,这就是为什么我不认为这是原因。

Package 结构(不要与名称 Aerospike 混淆)

我现在为此花费了太多时间,我真的非常渴望帮助,希望您能帮助我,或者至少为我指明正确的方向。

编辑

这是整个 RestController:

@Controller
public abstract class CoreController<S extends CoreService<T>, T extends CoreEntity> {

    public static final String SERVER = "http://localhost", PORT = ":8080",
        CORE_API = SERVER + PORT + "/"; // controller/v2/
    public static final String ID = "id";
    private String api;

    public CoreController() { }
    public CoreController(final String api) { this.api = CORE_API + api; }

    @RequestMapping(value = "/{" + ID + "}", method = RequestMethod.GET)
    public ResponseEntity<T> getById(@PathVariable final long id) {
        System.out.println("TEST ===> " + id);
        T entity = getService().getById(id);
        return entity == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(entity);
    }

    public abstract S getService();
}

@Controller
@RequestMapping(value = "pets/")
public class PetController extends CoreController<PetService, Pet> {

    @Autowired
    protected PetService service;
    public static final String API = "pets";

    public PetController() { super(API); }

    public PetService getService() { return service; }
}

这里有证据表明 spring-boot 正在侦听 8080 并且 postman 与端口 8080 一起工作。

服务器在启动时打印出来

我认为您在开头缺少斜杠(“/”),并且在暴露值的末尾有重复,因此它正在寻找 pets//{id} 在 controller 更改为 value = {“/pets”} 无论如何,启动服务时,您应该在日志中看到暴露的 uri

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM