【问题标题】:How to post body in sitebricks-client?如何在 sitebricks-client 中发布正文?
【发布时间】:2012-09-16 20:38:55
【问题描述】:

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

【问题讨论】:

    标签: java rest post rest-client sitebricks


    【解决方案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);
    

    如果您有一个包含要发送到内容类型为“application/json”的服务器的数据的地图,那么您可能会遇到这样的事情:

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

    上面的例子有两点需要注意:

    • 传递给post 方法的值应该是传递给transports 方法的类型。
    • 传递给over 方法的类决定了Content-Type 标头的默认值以及传递给post 方法的值的序列化方式。该类应该是com.google.sitebricks.client.Transport 的子类,您可能需要选择com.google.sitebricks.client.transport 包中的类之一。

    【讨论】:

      【解决方案2】:

      我已经注意到尝试过,但是 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

      【讨论】:

      • 有一个 POST 方法,但我看不到它如何让我设置我最初的问题所要求的请求的主体 - 如何使用非空主体执行 POST
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      相关资源
      最近更新 更多