0

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);

可能であれば、jetty API クライアントを使用して同じことをしたいと思っています。

ありがとう。

4

2 に答える 2

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);
于 2015-11-11T13:22:16.253 に答える
0

Apache HttpClientとのセッションを保持するには、HttpClientインスタンスを一度作成してから、すべてのリクエストで再利用する必要があります。

Jetty HTTP クライアント API がどのように機能するかはわかりませんが、一般的には、POST 要求を作成し、UTF-8 バイトとしてエンコードされた JSON データを要求コンテンツとして追加するだけです。

于 2013-11-05T14:52:19.730 に答える