【问题标题】:POST with JSON body consumed by RESTeasy - HTTP 100RESTeasy 使用 JSON 正文的 POST - HTTP 100
【发布时间】:2012-04-12 13:59:20
【问题描述】:

我有一个非常简单的场景,我无法开始工作。我正在尝试使用 cURL 将 JSON 字符串发布到 RESTful endoint,以通过服务器上的 HTTPS 和 RESTeasy 发送请求。

我的 cURL POST 是这样配置的:

$ch = curl_init();

$content = json_encode($validJsonString);

curl_setopt($ch, CURLOPT_URL, 'https://foobar.com/test?trackingId=12345');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $content));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);

$headers = array( 
    'Content-Type: application/json',
    'Content-Length: ' . strlen($content)
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec ($ch);

$httpResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$json = json_decode($response);
curl_close ($ch);

return $json;

RESTeasy 接收者看起来像:

@POST
@Path("/test")
@Produces("application/json")
public String addObjectCommentAsJSON(   @FormParam("json") String validJsonString, 
                                        @QueryParam("trackingId") String trackingId) {
    Gson gson = new Gson();
    SomeObject someObject = gson.fromJson(validJsonString, SomeObject.class);
    String responseString = methodThatReturnsAJsonString(trackingId, someObject);
    return responseString;
}

我遇到的这个问题是请求挂起大约 30 秒,然后返回 HTTP 100 响应。我知道 HTTP 100 意味着继续请求的其余部分,但我不明白我应该怎么做。

我试图删除 Content-Length 标头,但显然我得到了 411(需要内容长度),所以这也不是一个选项。

这可能是内容类型的问题吗?非常感谢任何帮助。

【问题讨论】:

  • 根据 php.net,如果您将数组传递给 CURLOPT_POSTFIELDS,它将被编码为 multipart/form-data。如果直接传递json字符串会发生什么?
  • @cbuckley 我看到了,但是在其他地方没有提到 RESTeasy,这是 50% 的潜在问题......
  • @abraham 我不知道...我试试看。
  • 请参阅 abraham 对此处问题的评论。如果 content-type 是 application/json,则应该给 CURLOPT_POSTFIELDS 一个包含 json_encode 输出的字符串。

标签: php rest post curl resteasy


【解决方案1】:

好的,感谢@cbuckley 和@abraham 在他们的 cmets 中的建议,我能够解决这些问题。这是我需要做的:

1-> 更改 POST 正文的内容,所以我现在有 curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $content)); 而不是 curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($validJsonString));

2-> 我创建了一个自定义 @Provider,它将 JSON 字符串解析为具有相同结构的 Java POJO:

@Provider
public class SomeObjectProvider implements StringConverter<SomeObject> {

    private final Gson gson = new Gson();
    public SomeObject fromString(String s) {
        return gson.fromJson(s, SomeObject.class);
    }

    public String toString(SomeObject someObject) {
        return gson.toJson(SomeObject);
    } 
}

3-> 最后,receiver 方法的结构要稍微改变一下:

@POST
@Path("/test")
@Produces("application/json")
public String addObjectCommentAsJSON(SomeObject someObject,
                                     @QueryParam("trackingId") String trackingId) {
    String responseString = methodThatReturnsAJsonString(trackingId, someObject);
    return responseString;
}

这一切都很顺利。

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多