Jetty 9 - 如何使用Jetty 9设置“请求内容”和“请求标头”?

时间:2014-07-23 20:26:19

标签: java jetty

我使用Jetty 7的ContentExchange类来设置URL,标题和requestContent。

以下是我使用Jetty 7的内容。

    HttpClient client = new HttpClient();
    client.start();
    ContentExchange exchange = new ContentExchange();
    exchange.setURL(url);
    exchange.setRequestHeader("Content-Type", "application/xml");
    exchange.setRequestHeader("Authorization", "Basic " + this.getAuthenticatonString());
    exchange.setMethod("POST");

    final AbstractBuffer cb = new ByteArrayBuffer(xml.getBytes("UTF-8"));
    exchange.setRequestContent(cb);

    client.send(exchange);
    exchange.waitForDone();


Jetty 9没有ContentExchange类,但经过一些研究我得到了这个

HttpClient client = new HttpClient();
client
.POST(url)
.send()


我想我可以使用client.param设置请求标题,但我对此并不十分肯定。

所以我的问题是如何使用Jetty 9设置“请求内容”和“请求标题”?

2 个答案:

答案 0 :(得分:0)

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.Request;
import org.eclipse.jetty.client.ContentResponse;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpHeader;
...
HttpClient client = new HttpClient();
client.start();
Request req = client.newRequest("http://....");
req.method(HttpMethod.GET);
req.agent("Mozilla/5.0...");
req.header(HttpHeader.ACCEPT, "text/html");
req.header(HtppHeader.CONNECTION, "Keep-Alive");
ContentResponse resp = req.send():
...
client.stop();

答案 1 :(得分:0)

除了上面的答案,

我在使用 Jetty 11 Http Client 时发现 req.header 在最新版本中已被弃用。 ( 11.0.5 ).

因此,我不得不想办法使用 Jetty Http Client 11 发送身份验证标头。

我就是这样做的。注意第 4 行。

    httpClient.start();
    URI uri = UriBuilder.fromUri(URI.create(ENDPOINT)).path("v1/testPath").queryParam("testParam","testValue").build();
    InputStreamResponseListener listener = new InputStreamResponseListener(); //Required for large responses only
    httpClient.newRequest(uri).method(HttpMethod.GET).headers(httpFields -> httpFields.add("Authorization","Bearer "+token)).send(listener);
    Response response =  listener.get(20, TimeUnit.SECONDS);
    if(response.getStatus() == 200){
        //doSomething.
    }