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

标签 java mongodb spring-boot httpurlconnection

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

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

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;
}

http://www.google.com 的回复或任何其他主页都成功,状态代码为 200。但是,一旦我调用 API,我就会收到状态代码 404 的错误。奇怪的是,当我使用 Postman 或浏览器时,一切正常。因此,当我通过 postman 向以下方法( http://localhost:8080/pets/3 )发出 get 请求时,我可以看到打印输出并从 mongodb 获取数据,但不能看到上面的代码。对于上面的代码,服务器端没有任何反应,没有打印,没有异常,什么也没有。

@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 Structure (Don't be confused from name 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。

Server print out on start up

最佳答案

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

关于java - 调用 spring-boot API 时出现状态码 404,但不适用于 postman 或浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58144541/

相关文章:

java - 从 JBoss AS 7 上的类路径加载 URL 资源

java - Oracle AQ 出队顺序

MongoDb 数据库与集合

javascript - 如何使用 node.js 将 _bsontype objectID 值转换为 string/objectID 以插入到 mongoDB 中

java - Spring Boot 希望@Component 类成为@Configuration 类中的@Bean

java - 如何不断要求用户选择有效选项?

java - 如何使用 Espresso + JMockit

javascript - 在异步函数中使用 While 循环?

java - 尽管 @JsonIgnore,Jackson 集合序列化器仍出现错误

java - JAX-RS( Jersey )和 Jackson 未正确序列化 LocalDate