我正在使用Jetty HTTP客户端发送请求,在下面的测试用例中我想测试已成功添加有效负载: 但我无法从Request [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
答案 0 :(得分:1)
嗯,你在StringContentProvider
放了一个,这样你就可以得到getContent()。但实际上你并不需要知道,因为afaik(不适用于jetty客户端)你只需要ContentProvider接口......
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特定的; - )。