我需要调用的Web服务返回"两个不同的响应对象"在运行时没有任何标题或元数据来区分它们。
唯一的方法是在客户端读取和转换输入流。我想知道这可能会让休息变得容易吗?
答案 0 :(得分:0)
我们必须定义一个消息体阅读器,在那里我们可以决定要传输哪个对象。这是一个示例代码:
ResteasyProviderFactory restProviderFactory = ResteasyProviderFactory.getInstance();
RegisterBuiltin.register(restProviderFactory);
restProviderFactory.addMessageBodyReader(MyRestResponseReader.class);
HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
ClientExecutor executor = new ApacheHttpClientExecutor(httpClient);
MyRestInterface client = ProxyFactory.create(MyRestInterface.class, url, executor);
ClientResponse<Object> res = client.get(request);
Object output = res.getEntity();
public class MyRestResponseReader implements MessageBodyReader<Object> {
public boolean isReadable(Class clazz, Type type, Annotation[] annptation, MediaType mediaType) {
return Object.class.isAssignableFrom(clazz);
}
public Object readFrom(Class clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap map, InputStream inputStream)
throws IOException, WebApplicationException {
try{
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String allLines = "";
String line = "";
while( (line = bufferedReader.readLine()) != null){
allLines = allLines + line;
}
if(allLines.contains("...")){
JAXBContext jaxbContext = JAXBContext.newInstance(MyResponseA.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(allLines);
return (MyResponseA) unmarshaller.unmarshal(reader);
}else if (allLines.contains("validationResponse")){
JAXBContext jaxbContext = JAXBContext.newInstance(MyResponseB.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(allLines);
return (MyResponseB) unmarshaller.unmarshal(reader);
}
}catch(Exception e){
}
return null;
}
}
public interface MyRestInterface {
@POST
@Consumes({"application/xml"})
@Produces({"application/xml"})
public ClientResponse<Object> get(ValidationRequest req);
}