如何从Play WSClient的字符串创建WSResponse对象 [英] How to create a WSResponse object from string for Play WSClient

查看:185
本文介绍了如何从Play WSClient的字符串创建WSResponse对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档建议基于API客户端进行测试使用模拟Web服务在WSClient上运行,即创建一个play.server.Server,它将响应实际的HTTP请求.

Documentation suggests testing API client based on WSClient using a mock web service, that is, create a play.server.Server which will respond to real HTTP requests.

我希望直接从文件创建WSResponse对象,并带有状态行,标头行和正文,而无需真正的TCP连接.这将需要更少的依赖关系并运行得更快.在某些情况下,这很有用.

I would prefer to create WSResponse objects directly from files, complete with status line, header lines and body, without real TCP connections. That would require less dependencies and run faster. Also there may be other cases when this is useful.

但是我找不到一种简单的方法来做到这一点.似乎所有由WSResponse包装的实现都与从网络中读取有关.

But I can't find a simple way to do it. It seems all implementations wrapped by WSResponse are tied to reading from network.

我是否应该为此创建自己的WSResponse子类,或者我错了并且它已经存在?

Should I just create my own subclass of WSResponse for this, or maybe I'm wrong and it already exists?

推荐答案

Play API似乎是故意钝化的.您必须使用它们的可缓存"类,这是唯一可以从您周围的对象直接实例化的类.

The API for Play seems intentionally obtuse. You have to use their "Cacheable" classes, which are the only ones that seem directly instantiable from objects you'd have lying around.

这应该使您入门:

import play.api.libs.ws.ahc.AhcWSResponse;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseBodyPart;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseHeaders;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseStatus;
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders;
import play.shaded.ahc.org.asynchttpclient.Response;
import play.shaded.ahc.org.asynchttpclient.uri.Uri;

AhcWSResponse response = new AhcWSResponse(new Response.ResponseBuilder()
        .accumulate(new CacheableHttpResponseStatus(Uri.create("uri"), 200, "status text", "protocols!"))
        .accumulate(new CacheableHttpResponseHeaders(false, new DefaultHttpHeaders().add("My-Header", "value")))
        .accumulate(new CacheableHttpResponseBodyPart("my body".getBytes(), true))
        .build());

未记录神秘的布尔值.我的猜测是BodyPart的布尔值是那是否是身体的最后一部分.我对标头的猜测是标头是否在邮件的预告片中.

The mystery boolean values aren't documented. My guess is the boolean for BodyPart is whether that is the last part of the body. My guess for Headers is whether the headers are in the trailer of a message.

这篇关于如何从Play WSClient的字符串创建WSResponse对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆