【问题标题】:POST json to REST from php将 json 从 php 发布到 REST
【发布时间】:2012-12-13 09:31:57
【问题描述】:

我有一个 REST url(使用 DropWizard 在 Java 中编码),我想从 PHP 向其 POST 一个 json。但是我收到415 Unsupported MediaType 错误。我查看了许多论坛,但无法弄清楚错误可能是什么。我的两端代码如下:

服务器

@POST
@Path("/update-table")
@Timed
public TableUpdateResponse updateTable(TestClass testObj) {
    LOG.info("inside updateTable function");
    //other code ...
}

客户

<?php

$url = "localhost:8084/update-table"
$ch = curl_init($url);

$jsonString = array("testString" => "Hello World!");            
$json =  json_encode($jsonString);

$headers = array();
$headers[] = 'Content-Type: application/json';

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$response = curl_exec($ch);
echo $response;

?>

TestClass

public class TestClass {
    private String testString;

    public TestClass(String testString) {
        super();
        this.testString = testString;
    }

    public TestClass() {
        super();
    }

    public String getTestString() {
        return testString;
    }

    public void setTestString(String testString) {
        this.testString = testString;
    }

}

请求未达到 REST(未打印 LOG 行)。我在这里错过了什么?

【问题讨论】:

    标签: rest http-post dropwizard


    【解决方案1】:

    尝试将 application/json 内容类型更改为其中之一

    application/json
    application/x-javascript
    text/javascript
    text/x-javascript
    text/x-json
    

    虽然 RFC 中指定的正确的是 application/json,但您的 java 代码可能有问题

    【讨论】:

    • 我猜问题出在 PHP 代码上,因为我从终端尝试了 curl 命令,它可以工作。
    【解决方案2】:

    添加注解@Consumes(MediaType.APPLICATION_JSON)

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 2015-10-14
      • 1970-01-01
      • 2016-05-21
      • 2016-02-10
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多