如何使用Jetty http客户端将json作为请求主体发布?

时间:2015-11-11 11:14:04

标签: java post jetty

我很难将JSON添加到POST请求正文中。没有任何方法可以设置请求的主体。

我有什么办法可以做到这一点。否则我不得不放弃使用Jetty。

这就是我发布POST请求的方式:

Request request = httpClient.POST(url);
        //request.method(HttpMethod.POST);
        request.header(HttpHeader.ACCEPT, "application/json");
        request.header(HttpHeader.CONTENT_TYPE, "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);

感谢任何帮助!

2 个答案:

答案 0 :(得分:5)

我能够自己解决这个问题。解决方案一直盯着我看。

添加了一行,一切正常:

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

希望它对其他人也有帮助。

答案 1 :(得分:0)

感谢 你解决了困扰我很久的问题。

/*配置sslcontextfactory处理https请求*/
        SslContextFactory sslContextFactory = new SslContextFactory();
        HttpClient httpClient = new HttpClient(sslContextFactory);
        httpClient.setFollowRedirects(false);
        httpClient.start();

        /*配置post请求的url、body、以及请求头*/
        Request request =  httpClient.POST("https://a1.easemob.com/yinshenxia/yinshenxia/users");
        request.header(HttpHeader.CONTENT_TYPE, "application/json");
        request.content(new StringContentProvider("{\"username\":\"jliu\",\"password\":\"123456\"}","utf-8"));
//      request.param("username", "jliu");
//      request.param("password", "123456");
        ContentResponse response = request.send();
        String res = new String(response.getContent());
        System.out.println(res);
        httpClient.stop();
相关问题