【问题标题】:How can I send a JSON request using Jetty API Client?如何使用 Jetty API 客户端发送 JSON 请求?
【发布时间】:2013-11-05 12:49:34
【问题描述】:

我正在尝试使用 Jetty HttpClient 将 JSON 字符串发送到服务器,但我没有找到任何关于如何做到这一点的好例子,只请求客户端通过 POST 发送简单参数的位置。

我设法使用 Apache HttpClient 发送请求,但是当我执行下一个请求时,我遇到了保持会话的问题。

// rpcString is a json like  {"method":"Login","params":["user","passw"],"id":"1"}:
entity = new StringEntity(rpcString, HTTP.UTF_8);
HttpPost httpPost = new HttpPost("http://site.com:8080/json/users");
entity.setContentType("application/json");
httpPost.setEntity(entity);
client = HttpClientBuilder.create().build();
CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpPost);

如果可能的话,我喜欢使用码头 API 客户端做同样的事情。

谢谢。

【问题讨论】:

  • 上面的代码应该可以工作。您遇到了哪些具体错误?
  • 是的,它可以工作,但这是一个使用 Apache HttpClient 而不是 Jetty 的示例,我喜欢使用 Jetty,然后也具有异步功能。
  • @pabl0x 我刚刚提供了 Jetty 版本。这里使用最新的 jetty-client 9.3.5.v20151012

标签: java json jetty httpclient


【解决方案1】:

这个问题真的很老了,但我遇到了同样的问题,这就是我解决它的方法:

        // Response handling with default 2MB buffer
        BufferingResponseListener bufListener = new BufferingResponseListener() {
        @Override
        public void onComplete(Result result) {

            if (result.isSucceeded()) {
                // Do your stuff here
            }

        }
    };        

    Request request = httpClient.POST(url);
    // Add needed headers
    request.header(HttpHeader.ACCEPT, "application/json");
    request.header(HttpHeader.CONTENT_TYPE, "application/json");

    // Set request body
    request.content(new StringContentProvider(JSON_STRING_HERE), "application/json");


    // Add basic auth header if credentials provided
    if (isCredsAvailable()) {
        String authString = username + ":" + password;
        byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
        String authStringEnc = "Basic " + new String(authEncBytes);
        request.header(HttpHeader.AUTHORIZATION, authStringEnc);
    }

    request.send(bufListener);

【讨论】:

    【解决方案2】:

    要保留与Apache HttpClient 的会话,您需要创建HttpClient 实例一次,然后将其重用于所有请求。

    我不知道 Jetty HTTP 客户端 API 是如何工作的,但一般来说,您只需要构建一个 POST 请求并将编码为 UTF-8 字节的 JSON 数据添加为请求内容。

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2015-07-02
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      相关资源
      最近更新 更多