【问题标题】:Problems curling from PHP - Spring 3 REST PUT/POST methods using @RequestParameter parameters来自 PHP 的问题 - 使用 @RequestParameter 参数的 Spring 3 REST PUT/POST 方法
【发布时间】:2012-07-08 04:31:04
【问题描述】:

我使用 Spring 框架为 REST 服务创建了一个非常简单的控制器。我将 @PathVariable 与 GET 结合使用没有任何问题,但是当我尝试创建 POST 或 PUT 时,我无法 curl 函数并试图找出我哪里出错了。

@Controller
public class TestController {


    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public String putName(@RequestParam("name") String name, @RequestParam("value") String value) {

        System.out.println("Name - " + name);
        System.out.println("Value - " + value);


        return "You entered " + name + " with value of " + value;
    }
}

稍微编辑一下以包含一些 PHP,因为这最终是我想要调用它的地方。

如果我执行以下操作,它会按预期工作:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://localhost:8080/RestService/test');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'name=some random name&value=just a value');
    $result = curl_exec($ch);

但如果我尝试将参数作为数组传递,我会收到 HTTP 状态 400 - 客户端发送的请求在语法上不正确。

    $data = array
    (
        'name' => 'some random name',
        'value' => 'just a value'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://localhost:8080/RestService/test');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result2 = curl_exec($ch);

如果我能帮上忙,我不想在我想要传递的数据中构建字符串、担心转义 & 等。

非常感谢任何帮助。

【问题讨论】:

  • 你试过这个命令curl --data "name=test" http://localhost:8080/RestService/test 吗?

标签: java php web-services spring rest


【解决方案1】:

使用 http_build_query

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

【讨论】:

  • 这确实适用于 POST - 但如果我在服务器端将方法更改为 PUT,并在客户端进行适当的更改,所有表单都返回 HTTP 状态 400 - 发送的请求客户端在语法上不正确。我在服务器端做错了吗??
  • 你有这个方法的 Spring Security 配置吗?也许有一个拦截 URL 配置为允许 POST 但不允许 PUT?
  • 如果我这样做,那不是故意的。那会在上下文 xml 文件中吗?
猜你喜欢
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多