标签:
org.apache.cxf.jaxrs.client.WebClient
@GET @Path("/echo/{input}") @Produces("text/plain") public String ping(@PathParam("input") String input) { return input; }
@Test public void testPing() throws Exception { WebClient client = WebClient.create(serverUrl + "/c/echo/SierraTangoNevada"); Response r = client.accept("text/plain").get(); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); String value = IOUtils.toString((InputStream)r.getEntity()); assertEquals("SierraTangoNevada", value); }
@POST @Produces("application/json") @Consumes("application/json") @Path("/jsonBean") public Response modifyJson(InputBean input) { input.setVal2(input.getVal1()); return Response.ok().entity(input).build(); }
@Test public void testJsonRoundtrip() throws Exception { // List<Object> providers = new ArrayList<Object>(); // providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider()); List<org.codehaus.jackson.jaxrs.JacksonJsonProvider> provider = Collections.singletonList(new org.codehaus.jackson.jaxrs.JacksonJsonProvider()); InputBean inputBean = new InputBean(); inputBean.setVal1("Maple"); WebClient client = WebClient.create(serverUrl + "/c/jsonBean", provider); InputBean jsonBean = client.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .post(inputBean,InputBean.class); System.out.println(jsonBean.toString()); // assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); // MappingJsonFactory factory = new MappingJsonFactory(); // JsonParser parser = factory.createJsonParser((InputStream)r.getEntity()); // JsonBean output = parser.readValueAs(JsonBean.class); // assertEquals("Maple", output.getVal2()); }
get
WebClient org.apache.cxf.jaxrs.client.WebClient.create(String baseAddress)
post
WebClient org.apache.cxf.jaxrs.client.WebClient.create(String baseAddress, List<?> providers)
List<Object> providers = new ArrayList<Object>(); providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
List<org.codehaus.jackson.jaxrs.JacksonJsonProvider> provider = Collections.singletonList(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
// Set HTTP Accept header // Set HTTP Content-Type header // javax.ws.rs.core.MediaType webClient.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
public <T> T post(Object body, Class<T> responseClass)
例如:
JsonBean inputBean = new JsonBean();[...] JsonBean jsonBean = client.accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .post(inputBean,JsonBean.class);
标签:
原文地址:http://www.cnblogs.com/zno2/p/4689510.html