Java Code Examples for javax.ws.rs.client.WebTarget#request()

The following examples show how to use javax.ws.rs.client.WebTarget#request() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SigningTest.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerification() throws Exception
{
   Verifier verifier = new Verifier();
   Verification verification = verifier.addNew();
   verification.setRepository(repository);

   WebTarget target = client.target("http://localhost:9095/signed");
   Invocation.Builder request = target.request();
   request.property(Verifier.class.getName(), verifier);
   Response response = request.get();

   System.out.println(response.getHeaderString(DKIMSignature.DKIM_SIGNATURE));
   Assert.assertEquals(200, response.getStatus());

   // If you don't extract the entity, then verification will not happen
   System.out.println(response.readEntity(String.class));
   response.close();
}
 
Example 2
Source File: AsyncJobTest.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsynch() throws Exception
{
   Client client = ClientBuilder.newClient();
   WebTarget target = client.target("http://localhost:9095/resource?asynch=true");
   Entity<String> entity = Entity.entity("content", "text/plain");
   Invocation.Builder builder = target.request(); 
   Response response = builder.post(entity);//.readEntity(String.class);

   Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
   String jobUrl1 = response.getStringHeaders().getFirst(HttpHeaders.LOCATION);
   System.out.println("jobUrl1: " + jobUrl1);
   response.close();
   
   target = client.target(jobUrl1);
   Response jobResponse = target.request().get();

   Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
   jobResponse.close();
   
   Thread.sleep(1500);
   response = client.target(jobUrl1).request().get();
   Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
   Assert.assertEquals("content", response.readEntity(String.class));
}
 
Example 3
Source File: InstanceProviderClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
public InstanceConfirmation postRefreshConfirmation(InstanceConfirmation confirmation) {
    WebTarget target = base.path("/refresh");
    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
    Response response;
    try {
        response = invocationBuilder.post(Entity.entity(confirmation, MediaType.APPLICATION_JSON));
    } catch (Exception ex) {
        LOGGER.error("Unable to confirm refresh object for {}/{}.{}: {}", confirmation.getProvider(),
                confirmation.getDomain(), confirmation.getService(), ex.getMessage());
        throw new ResourceException(ResourceException.GATEWAY_TIMEOUT, ex.getMessage());
    }
    int code = response.getStatus();
    if (code == ResourceException.OK) {
        return response.readEntity(InstanceConfirmation.class);
    }
    throw new ResourceException(code, responseText(response));
}
 
Example 4
Source File: FHIROAuth2Test.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = { "testRegisterClient" })
public void testTokenRequest() throws Exception {
    if (ON) {
        WebTarget endpoint = client.getWebTarget(tokenURL);
        Form form = new Form();
        form.param("grant_type", "client_credentials").param("client_id", clientID.replaceAll("\"", "")).param("client_secret", clientSecret.replaceAll("\"", ""));

        Entity<Form> entity = Entity.form(form);
        Invocation.Builder builder = endpoint.request("application/json");
        Response res = builder.post(entity);
        assertResponse(res, Response.Status.OK.getStatusCode());
        JsonObject resJson = res.readEntity(JsonObject.class);
        assertNotNull(resJson.get("access_token"));
        accessToken = resJson.get("access_token").toString();
        System.out.println("accessToken = " + accessToken);
    } else {
        System.out.println("testTokenRequest Disabled, Skipping");
    }
}
 
Example 5
Source File: FHIRClientImpl.java    From FHIR with Apache License 2.0 6 votes vote down vote up
@Override
public FHIRResponse invoke(String resourceType, String operationName, FHIRParameters parameters, FHIRRequestHeader... headers) throws Exception {
    if (resourceType == null) {
        throw new IllegalArgumentException("The 'resourceType' argument is required but was null.");
    }
    if (operationName == null) {
        throw new IllegalArgumentException("The 'operationName' argument is required but was null.");
    }
    WebTarget endpoint = getWebTarget();
    endpoint = endpoint.path(resourceType).path(operationName);
    endpoint = addParametersToWebTarget(endpoint, parameters);
    Invocation.Builder builder = endpoint.request(getDefaultMimeType());
    builder = addRequestHeaders(builder, headers);
    Response response = builder.get();
    return new FHIRResponseImpl(response);
}
 
Example 6
Source File: RestDemoServiceIT.java    From demo-rest-jersey-spring with MIT License 6 votes vote down vote up
@Test
public void testGetLegacyPodcast() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/2");

	Builder request = webTarget.request(MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	Podcast podcast = response.readEntity(Podcast.class);

	ObjectMapper mapper = new ObjectMapper();
	System.out
			.print("Received podcast from LEGACY database *************************** "
					+ mapper.writerWithDefaultPrettyPrinter()
							.writeValueAsString(podcast));

}
 
Example 7
Source File: SendFormData.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public void post(SendFormDataPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
    MultivaluedMap multiValuedMap = new MultivaluedHashMap();
    if (body.getParam1()!= null) {
        multiValuedMap.add("param1", body.getParam1().toString());
    }
    if (body.getParam2()!= null) {
        multiValuedMap.add("param2", body.getParam2().toString());
    }
    Response response = invocationBuilder.post(Entity.entity(multiValuedMap, javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED_TYPE));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new TestsendformdataException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
}
 
Example 8
Source File: Foo.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public FooResponse<same_path_multiple_times.resource.foo.model.FooGETResponseBody> get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    FooResponse<same_path_multiple_times.resource.foo.model.FooGETResponseBody> apiResponse = new FooResponse<same_path_multiple_times.resource.foo.model.FooGETResponseBody>(response.readEntity(same_path_multiple_times.resource.foo.model.FooGETResponseBody.class), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example 9
Source File: RestDemoServiceIT.java    From demo-restWS-spring-jersey-jpa2-hibernate with MIT License 5 votes vote down vote up
@Test
public void testGetPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-spring-jersey-jpa2-hibernate-0.0.1-SNAPSHOT/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present",
			podcasts.size() > 0);
}
 
Example 10
Source File: ServiceConnector.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
public Response getResponseFromEndpoint(String url, MediaType mediaType) {
    System.out.println("Getting object from url " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.accept(mediaType).get();
    client.close();
    return response;
}
 
Example 11
Source File: Provider.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns combined provider details
 * 
 */
public library.resource.provider.model.ProviderGETResponse get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new CoreServicesAPIReferenceException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    return response.readEntity(library.resource.provider.model.ProviderGETResponse.class);
}
 
Example 12
Source File: Login.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public FooResponse<List<AuthorizationJson>> post() {
        WebTarget target = this._client.target(getBaseUri());
        final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
        Response response = invocationBuilder.post(null);
        if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
            Response.StatusType statusInfo = response.getStatusInfo();
            throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
        }
        FooResponse<List<AuthorizationJson>> apiResponse = new FooResponse<List<AuthorizationJson>>(response.readEntity((
new javax.ws.rs.core.GenericType<java.util.List<java_8_dates.resource.cs.login.model.AuthorizationJson>>() {})), response.getStringHeaders(), response);
        return apiResponse;
    }
 
Example 13
Source File: RestDemoServiceIT.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 5 votes vote down vote up
@Test
public void testGetPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-spring-jersey-tomcat-mybatis-0.0.1-SNAPSHOT/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present",
			podcasts.size() > 0);
}
 
Example 14
Source File: EndpointTest.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example 15
Source File: Login.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public simple.resource.cs.login.model.LoginPOSTResponse post(LoginPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.post(Entity.json(body));
    if (response.getStatusInfo().getFamily()!= javax.ws.rs.core.Response.Status.Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    return response.readEntity(simple.resource.cs.login.model.LoginPOSTResponse.class);
}
 
Example 16
Source File: NotificationTest.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public Response processRequest(String url, String method, String payload)
    throws GeneralSecurityException, IOException {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  builder.header(
      HttpHeaders.AUTHORIZATION,
      "Bearer "
          + new JWTVerifier()
              .createJWT("fred", new HashSet<String>(Arrays.asList("orchestrator"))));
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
 
Example 17
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public String get(String url) {

		Client client = ClientBuilder.newClient();

		WebTarget resource = client.target(url);

		Builder request = resource.request();
		request.accept(MediaType.TEXT_PLAIN);

		return request.get(String.class);

	}
 
Example 18
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public<T> T post(String url, Object payload,Class<T> type) {
	Client client = ClientBuilder.newClient();

	WebTarget resource = client.target(url);

	Builder request = resource.request();
	request.accept(MediaType.APPLICATION_JSON);

	return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}
 
Example 19
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public<T> T post(String url, Object payload,Class<T> type) {
	Client client = ClientBuilder.newClient();

	WebTarget resource = client.target(url);

	Builder request = resource.request();
	request.accept(MediaType.APPLICATION_JSON);

	return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}
 
Example 20
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public String getJson(String url) {

		Client client = ClientBuilder.newClient();

		WebTarget resource = client.target(url);

		Builder request = resource.request();
		request.accept(MediaType.APPLICATION_JSON);

		return request.get(String.class);

	}