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

new9mtju  于 2023-04-19  发布在  Java
关注(0)|答案(3)|浏览(258)

我使用Jetty 7的ContentExchange类来设置URL、headers和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设置“请求内容”和“请求头”?

4sup72z8

4sup72z81#

除了上述答案外,
我在使用Jetty 11 Http客户端时,发现req.header在最新版本(11.0.5)中已被弃用。
因此,我不得不想出一种方法,用Jetty Http Client 11发送身份验证头。
我是这样做的。注意第四行。

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.
    }
huus2vyu

huus2vyu2#

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

siotufzp3#

如果有人无意中发现文件,
对于内容的情况:req.post(OldWayOfcontentProviders)已弃用并替换为:req.body(Request.Content oneOfFollowingImplementations)
请参考utils(org.eclipse.jetty.client.util),其中一些预定义的实现示例-
ByteBufferRequestContent
StringRequestContent
MultiPartRequestContent ...
它们都有Request.Content接口的实现。
示例:

post.body(new ByteBufferRequestContent("text/xml", ByteBuffer.wrap("MyXMLContentAsString".getBytes)))

相关问题