我想从我的Rest Web Service创建的XML输出中获取属性值,但是在我的Java客户端中没有标记。我尝试过XPath,但它似乎不能使用URL,只能使用存储在驱动器中的XML文件。关于XPath的所有答案都专门用于存储的XML文件而不是在线。我正在使用Netbeans。概念是,Web服务需要两个数字并将总和作为XML提供。我在此示例http://localhost:8080/WSDemo/rest/book/5/2
休息网络服务
ApplicationConfig.java
package wbs;
import java.util.Set;
import javax.ws.rs.core.Application;
import javax.xml.bind.annotation.XmlRootElement;
@javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(wbs.GenericResource.class);
}
}
GenericResource.java
package wbs;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;
@Path("book")
public class GenericResource {
@Context
private UriInfo context;
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{n1}/{n2}")
public String getSum(@PathParam ("n1") int a, @PathParam ("n2") int b) {
int c = a+b;
return "<Sum>" + c + "</Sum>";
}
}
客户端
Sum.java
package restclient;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
public class Sum {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/WSDemo/rest/";
public Sum(){
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("book");
}
public <T> T getSum(Class<T> responseType, String n1, String n2) throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{n1, n2}));
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public void putXml(Object requestEntity) throws ClientErrorException {
webTarget.request(javax.ws.rs.core.MediaType.APPLICATION_XML).put(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_XML));
}
public void close() {
client.close();
}
}
RestClient.java
package com.emmanouil;
import restclient.Sum;
public class RestClient {
public static void main(String[] args) {
Sum client = new Sum();
String response = client.getSum (String.class,"5" , "2");
System.out.println(response);
client.close();
}
}
输出
我想清除标签并获得结果(在这种情况下为7)。当然,我可以修剪弦乐或任何其他类似的方式,但它是我不想做的事情。