0

我正在使用sitebricks-client与 Java 中的 REST API 进行交互。我需要用非空的身体做一个 POST。我如何在网站砖中做到这一点?

4

2 回答 2

1

您尚未指定要发布的请求正文类型。如果您尝试发送 Content-Type 为“text/plain”的字符串,则以下内容应该有效:

String body = "Request body.";
WebResponse response = web.clientOf(url)
    .transports(String.class)
    .over(Text.class)
    .post(body);

如果您尝试发送已经序列化为字符串的特定类型的数据,您可以手动设置 Content-Type 标头:

String body = "{}";
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
WebResponse response = web.clientOf(url, headers)
    .transports(String.class)
    .over(Text.class)
    .post(body);

If you have a Map containing data that you would like to send to the server with a Content-Type of "application/json", then something like this might be up your alley:

Map body = new HashMap();
// Fill in body with data
WebResponse response = web.clientOf(url)
    .transports(Map.class)
    .over(Json.class)
    .post(body);

There are two important points to pay attention to in the examples above:

  • The value passed to the post method should be of the type passed to the transports method.
  • The class that you pass to the over method determines the default value of the Content-Type header and the way in which the value passed to the post method is serialized. The class should be a subclass of com.google.sitebricks.client.Transport, and you will probably want to choose one of the classes found in the com.google.sitebricks.client.transport package.
于 2012-09-25T16:23:13.630 回答
0

我已经注意到尝试过,但是 webclient 中有一个 post() 方法。

web.clientOf("http://google.com")
...
.post(...);

查看github上的源码

https://github.com/dhanji/sitebricks/blob/master/sitebricks-client/src/main/java/com/google/sitebricks/client/WebClient.java

Rgds

于 2012-09-23T20:15:13.320 回答