gpt4 book ai didi

java - Jetty 9 HTTP客户端: How to get the request content?

转载 作者:行者123 更新时间:2023-12-01 11:02:02 25 4
gpt4 key购买 nike

我正在使用 Jetty HTTP 客户端发送请求,在下面的测试用例中我想测试负载是否已成功添加:但我找不到如何从请求中获取它[1]

这是我要测试的方法:

public Request createRequest (HttpClient httpClient, String url,HTTP_METHOD http_method, HashMap <String, String> headers,String payload, HashMap <String, String> params){

Request request;

request = httpClient.newRequest(url);
request.method(getHttpMethod(http_method));

/* add headers if any */
if(headers!=null){
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.header(entry.getKey(), entry.getValue());
}
}else{/*Nothing to do*/}

/* add params if any */
if(params!=null){
for (Map.Entry<String, String> entry : params.entrySet()) {
request.param(entry.getKey(), entry.getValue());
}
}else{/*Nothing to do*/}

/* add content if any*/
if(payload!= null){
request.content(new StringContentProvider(payload,"UTF-8"));
}else{/*Nothing to do*/}
return request;
}

这是我的测试用例:

@Test
public void testcreateRequestWithPayload() {

TestBackend testBackend = new TestBackend(3);
String url="http://www.google.com";

Request request= testBackend.createRequest(testBackend.getHttpClient(), url, HTTP_METHOD.PUT, null, "payload", null);

assertEquals("payload".length(),(request.getContent().getLength())); //not enough
}

我希望能够测试如下内容:

assertEquals("payload",(request.getContent())); 

[1] http://download.eclipse.org/jetty/9.3.3.v20150827/apidocs/org/eclipse/jetty/client/api/Request.html

最佳答案

好吧,您将一个 StringContentProvider 放在那里,这就是您将通过 getContent() 返回的内容。但实际上你不需要知道这一点,因为据我所知(不是用于 jetty 客户端)你只需要 ContentProvider 接口(interface)......

final ContentProvider provider = request.getContent();
final Iterator<ByteBuffer> it = provider.iterator();
while (it.hasNext()) {
final ByteBuffer next = it.next();
final byte[] bytes = new byte[next.capacity()];
next.get( bytes );
// Should by "payload"
String content = new String( bytes, Charset.forName( "UTF-8" ) );
}

(从未使用过 ByteBuffer,所以也许有一些更好的方法可以做到这一点,但您应该能够更轻松地找到相关文档,因为 ByteBuffer 是标准 java 而不是特定于 jetty 的;-)。

关于java - Jetty 9 HTTP客户端: How to get the request content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com