web-services - 如何对 REST 网络服务执行 POST 请求?

标签 web-services rest post

我有一个 RESTful 网络服务,我在其中编写了一个接收 POST 请求的方法。

我正在尝试通过 URL http://localhost:8091/prjctname/post 访问该方法。

但它抛出以下错误:

HTTP Status 405 - Request method 'GET' not supported
type: Status report
message: Request method 'GET' not supported
description: The specified HTTP method is not allowed for the requested resource

下面是代码片段。

@RequestMapping(value = "/post", method = RequestMethod.POST)
@Produces("application/json")
@ResponseBody 
public String createUser(@RequestBody PCDBean bean, HttpServletRequest request) {

    String username = null;
    String password = null;
    System.out.println("inside post method");

    String result = service.getCustomer(username, password);
    if(result != null) {
        return username + password;
    } else {
        return "failure";
    }
}

最佳答案

解释 405 错误

您正在对仅支持 POST 请求的端点执行 GET 请求。在这种情况下,预期结果是 405 错误:

6.5.5. 405 Method Not Allowed

The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. [...]

选择合适的工具

我猜您正在尝试使用浏览器地址栏 访问端点。但是,当在浏览器地址栏中键入资源 URL 时,您正在执行 GET 请求。这是浏览器的默认行为。 处理它

因此,一旦您只能从它执行 GET 请求,浏览器地址栏不会给您太多灵 active 来测试 REST API。

要测试 REST API,您应该使用正确的工具。他们将使您能够使用 all the HTTP methods 执行请求(包括POST),设置request headers以及浏览器地址栏中不可用的其他功能。

仅列出一些:

关于web-services - 如何对 REST 网络服务执行 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35839547/

相关文章:

java - 配置 Spring Web 服务以接受内容类型 text/xml Soap 1.2 消息

java - 从 Java 中的 SOAP C# Web 服务获取单个数据

Java继承接口(interface)中的注解

rest - 使用自签名证书和基本身份验证的Powershell Invoke-RestMethod-是否有示例?

在 AFNetworking 中使用 URL 参数和 JSON 正文进行 POST

windows - 如何实现WebServiceHost认证?

web-services - 何时使用 javax.ws.rs.core.Application 创建 RESTful Web 服务?

http - 如何处理 "100 continue"HTTP 消息?

ios - 如何在 Swift 中创建 GET、POST 和 PUT 请求?

java - spring @RequestParam Unicode 不正确