首页 > 解决方案 > Liferay Jax-RS:无法调用简单的 REST api,得到 403 和 405

问题描述

我正在使用 Liferay 7.3。

尝试使用 JAX-RS 构建 Rest API,我已按照此处的官方文档生成令牌https://help.liferay.com/hc/en-us/articles/360018166411-JAX-RS#using-oauth-20-to -invoke-a-jax-rs-web-service

@GET 得到 403 [Forbidden] 和 @POST 得到 405 [method not allowed]

package com.liferay.jaxrstest.application;

import java.util.Collections;
import java.util.Set;

import javax.ws.rs.*;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;

@Component(
    property = {
        JaxrsWhiteboardConstants.JAX_RS_APPLICATION_BASE + "=/greetings",
        JaxrsWhiteboardConstants.JAX_RS_NAME + "=Greetings.Rest"
    },
    service = Application.class
)
public class LiferaxJaxRsTestApplication extends Application {

    public Set<Object> getSingletons() {
        return Collections.<Object>singleton(this);
    }

    @GET
    @Produces("text/plain")
    public String working() {
        return "It works!";
    }

    @GET
    @Path("/morning")
    @Produces("text/plain")
    public String hello() {
        return "Good morning!";
    }

    @POST
    @Path("/morning")
    // @Produces("text/plain")
    // @Consumes("application/json")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String hello(User user) {
        return "Good morning!" + user.getFirstName();
    }
}

class User {

    private String firstName;
    
    public User(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
} 

在此处输入图像描述

标签: restjax-rsliferayliferay-7

解决方案


如果您尝试测试您创建的端点之一,则应使用为其创建的路径。

要测试早安 GET 端点,您应该对 URL 发出 GET 请求:

http://localhost:8080/o/greetings/morning

……没有身体。当您使用 OAuth2 时,您必须使用 Postman 中的“授权”选项卡传递令牌。在那里,您可以配置如何获取新令牌并使用它。

您应该如何配置它的图像

我还在考虑在门户控制面板中的 OAuth2 配置中,您在“范围”选项卡中选中了该服务GETPOST复选框。Greetings.Rest

最后,要获得clientIdclientSecret,请转到

控制面板 → 配置 → OAuth2 管理。


推荐阅读