[英]Jetty 9 HTTPclient: How to get the request content?
我正在使用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()返回的內容。 但是實際上您不需要知道,因為afaik(不是碼頭用戶常用的),您只需要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而不是碼頭專用的;-)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.