List of usage examples for org.apache.http.client.fluent Request Post
public static Request Post(final String uri)
From source file:AIR.Common.Web.HttpWebHelper.java
public String submitForm3(String url, Map<String, Object> formParameters, int maxTries, _Ref<Integer> httpStatusCode) throws IOException { Form f = Form.form();// ww w. j a v a 2 s .co m for (Map.Entry<String, Object> entry : formParameters.entrySet()) f.add(entry.getKey(), entry.getValue().toString()); for (int i = 1; i <= maxTries; i++) { try { return Request.Post(url).staleConnectionCheck(true).connectTimeout(getTimeoutInMillis()) .socketTimeout(getTimeoutInMillis()).version(HttpVersion.HTTP_1_1).bodyForm(f.build()) .execute().returnContent().asString(); } catch (Exception e) { httpStatusCode.set(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (i == maxTries) throw new IOException(e); } } // for some reason we ended here. just throw an exception. throw new IOException("Could not retrive result."); }
From source file:com.qwazr.search.index.IndexSingleClient.java
@Override public Response updateMappedDocsValues(String schema_name, String index_name, Collection<Map<String, Object>> documents) { try {/*from w ww.ja v a 2 s . c o m*/ UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/docs/values"); Request request = Request.Post(uriBuilder.build()); HttpResponse response = execute(request, documents, null); HttpUtils.checkStatusCodes(response, 200); return Response.status(response.getStatusLine().getStatusCode()).build(); } catch (HttpResponseEntityException e) { throw e.getWebApplicationException(); } catch (IOException e) { throw new WebApplicationException(e.getMessage(), e, Status.INTERNAL_SERVER_ERROR); } }
From source file:com.qwazr.search.index.IndexSingleClient.java
@Override public ResultDefinition.WithMap searchQuery(String schema_name, String index_name, QueryDefinition query, Boolean delete) {/*from w w w . j ava 2 s . c om*/ final UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/search") .setParameterObject("delete", delete); Request request = Request.Post(uriBuilder.build()); return commonServiceRequest(request, query, null, ResultDefinition.WithMap.class, 200); }
From source file:eu.trentorise.opendata.jackan.CkanClient.java
/** * * POSTs a body via HTTP. If {@link CkanResponse#isSuccess()} is false * throws {@link CkanException}.//from w w w. j a v a 2 s .c o m * * @param responseType * a descendant of CkanResponse * @param path * something like /api/3/action/package_create * @param body * the body of the POST * @param contentType * @param params * list of key, value parameters. They must be not be url * encoded. i.e. "id","laghi-monitorati-trento" * @throws CkanException * on error */ private <T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body, ContentType contentType, Object... params) { checkNotNull(responseType); checkNotNull(path); checkNotNull(body); checkNotNull(contentType); String fullUrl = calcFullUrl(path, params); T ckanResponse; String returnedText; try { LOG.log(Level.FINE, "Posting to url {0}", fullUrl); LOG.log(Level.FINE, "Sending body:{0}", body); Request request = Request.Post(fullUrl); configureRequest(request); Response response = request.bodyString(body, contentType).execute(); InputStream stream = response.returnResponse().getEntity().getContent(); try (InputStreamReader reader = new InputStreamReader(stream, Charsets.UTF_8)) { returnedText = CharStreams.toString(reader); } } catch (Exception ex) { throw new CkanException("Error while performing a POST! Request url is:" + fullUrl, this, ex); } try { ckanResponse = getObjectMapper().readValue(returnedText, responseType); } catch (Exception ex) { throw new CkanException( "Couldn't interpret json returned by the server! Returned text was: " + returnedText, this, ex); } if (!ckanResponse.isSuccess()) { throwCkanException("Error while performing a POST! Request url is:" + fullUrl, ckanResponse); } return ckanResponse; }
From source file:eu.eubrazilcc.lvl.oauth2.AuthTest.java
@Test public void test() { System.out.println("AuthTest.test()"); try {// ww w. ja va2s . com final String redirectURI = "https://localhost:8443/redirect"; final String state = generateFastUrlSafeSecret(); final String permissions = allPermissions(); final ResourceOwner resourceOwner = ResourceOwner.builder() .user(User.builder().userid("test_username").password("test_password") .email("username@example.com").firstname("Firstname").lastname("Lastname").role("user") .permissions(asPermissionList(permissions)).build()) .build(); RESOURCE_OWNER_DAO.insert(resourceOwner); // test client registration URI uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Registration.class).build(); System.out.println(" >> Client registration: " + uri.toString()); OAuthClientRequest request = OAuthClientRegistrationRequest .location(uri.toString(), OAuthRegistration.Type.PUSH).setName("Sample Application") .setUrl("http://www.example.com").setDescription("Description of a Sample App") .setIcon("http://www.example.com/app.ico").setRedirectURL(redirectURI).buildJSONMessage(); OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new URLConnectionClient()); OAuthClientRegistrationResponse response = oauthclient.clientInfo(request); assertThat("Registration response is not null", response, notNullValue()); assertThat("Registration client Id is valid", StringUtils.isNotBlank(response.getClientId())); assertThat("Registration client secret is valid", StringUtils.isNotBlank(response.getClientSecret())); assertThat("Registration expiration is valid", response.getExpiresIn(), notNullValue()); assertThat("Registration issued at is valid", StringUtils.isNotBlank(response.getIssuedAt())); final String clientId = response.getClientId(); final String clientSecret = response.getClientSecret(); /* uncomment the following lines for additional output */ System.out.println(" >> Client Id: " + response.getClientId()); System.out.println(" >> Client secret: " + response.getClientSecret()); System.out.println(" >> Expires in: " + response.getExpiresIn() + " seconds"); System.out.println(" >> Issued at: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(Long.parseLong(response.getIssuedAt()) * 1000l))); // test client authorization (end user) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build(); System.out.println(" >> Client (end user) authorization: " + uri.toString()); request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId) .setRedirectURI(redirectURI).setResponseType(ResponseType.CODE.toString()).setState(state) .buildQueryMessage(); HttpURLConnection conn = doRequest(request); String queryString = conn.getURL().toURI().getQuery(); Map<String, Object> map = OAuthUtils.decodeForm(queryString); assertThat("End user authorization code is not null", map.get(OAuth.OAUTH_CODE), notNullValue()); assertThat("End user authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE), equalTo(state)); /* uncomment the following lines for additional output */ for (final Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(" >> " + entry.getKey() + " -> " + entry.getValue()); } // test client authorization (token) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build(); System.out.println(" >> Client (token) authorization: " + uri.toString()); request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId) .setRedirectURI(redirectURI).setResponseType(ResponseType.TOKEN.toString()).setState(state) .buildQueryMessage(); conn = doRequest(request); String fragment = conn.getURL().toURI().getFragment(); map = OAuthUtils.decodeForm(fragment); assertThat("Token authorization expiration is not null", map.get(OAuth.OAUTH_EXPIRES_IN), notNullValue()); assertThat("Token authorization token is not null", map.get(OAuth.OAUTH_ACCESS_TOKEN), notNullValue()); /* uncomment the following lines for additional output */ for (final Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(" >> " + entry.getKey() + " -> " + entry.getValue()); } assertThat("Token authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE), equalTo(state)); // test access token (user & password) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build(); System.out.println(" >> Access token (user & password): " + uri.toString()); request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getUserid()) .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthJSONAccessTokenResponse response2 = oAuthClient.accessToken(request); assertThat("Access token is valid", response2.getAccessToken(), notNullValue()); assertThat("Access token expiration is not null", response2.getExpiresIn(), notNullValue()); assertThat("Access token permission is not null", response2.getScope(), notNullValue()); String accessToken = response2.getAccessToken(); /* uncomment the following lines for additional output */ System.out.println(" >> Access token: " + response2.getAccessToken()); System.out.println(" >> Expires in: " + response2.getExpiresIn() + " seconds"); System.out.println(" >> Scope: " + response2.getScope()); // test access token (email & password), this test uses an additional parameter in the request uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build(); System.out.println(" >> Access token (email & password): " + uri.toString()); request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getEmail()) .setPassword(resourceOwner.getUser().getPassword()).setParameter(OAuth2Token.USE_EMAIL, "true") // additional parameter .buildBodyMessage(); oAuthClient = new OAuthClient(new URLConnectionClient()); response2 = oAuthClient.accessToken(request); assertThat("Access token is valid (using email address)", response2.getAccessToken(), notNullValue()); assertThat("Access token expiration is not null (using email address)", response2.getExpiresIn(), notNullValue()); assertThat("Access token permission is not null (using email address)", response2.getScope(), notNullValue()); accessToken = response2.getAccessToken(); /* uncomment the following lines for additional output */ System.out.println(" >> Access token (using email address): " + response2.getAccessToken()); System.out .println(" >> Expires in (using email address): " + response2.getExpiresIn() + " seconds"); System.out.println(" >> Scope (using email address): " + response2.getScope()); // test token revocation request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getUserid()) .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage(); oAuthClient = new OAuthClient(new URLConnectionClient()); response2 = oAuthClient.accessToken(request); final String accessToken2 = response2.getAccessToken(); Path path = OAuth2TokenRevocation.class.getAnnotation(Path.class); System.out.println(" >> Token revocation: " + target.path(path.value()).getUri().toString()); Form form = new Form(); form.param("token", accessToken2); form.param("client_id", clientId); form.param("client_secret", clientSecret); Response response3 = target.path(path.value()).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); assertThat("Revoke token response is not null", response3, notNullValue()); assertThat("Revoke token response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Revoke token response is not empty", response3.getEntity(), notNullValue()); String payload = response3.readEntity(String.class); assertThat("Revoke token response entity is not null", payload, notNullValue()); assertThat("Revoke token response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Revoke token response body (JSON), empty is OK: " + payload); System.out.println(" >> Revoke token response JAX-RS object: " + response3); System.out.println(" >> Revoke token HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) create new user path = IdentityProvider.class.getAnnotation(Path.class); final User user = User.builder().userid("username2").password("password2") .email("username2@example.com").firstname("Firstname2").lastname("Lastname2").role("user") .permissions(asPermissionList(userPermissions(toResourceOwnerId("username2")))) .industry("Research").positions(newArrayList("positions")).build(); System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString()); response3 = target.path(path.value()).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)) .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Create new user response is not null", response3, notNullValue()); assertThat("Create new user response is CREATED", response3.getStatus(), equalTo(CREATED.getStatusCode())); assertThat("Create new user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Create new user response entity is not null", payload, notNullValue()); assertThat("Create new user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Create new user response body (JSON), empty is OK: " + payload); System.out.println(" >> Create new user response JAX-RS object: " + response3); System.out.println(" >> Create new user HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get users (JSON encoded) response3 = target.path(path.value()).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(); assertThat("Get users response is not null", response3, notNullValue()); assertThat("Get users response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Get users response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Get users response entity is not null", payload, notNullValue()); assertThat("Get users response entity is not empty", isNotBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Get users response body (JSON): " + payload); System.out.println(" >> Get users response JAX-RS object: " + response3); System.out.println(" >> Get users HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get users (Java object) final Users users = target.path(path.value()).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(Users.class); assertThat("Get users result is not null", users, notNullValue()); assertThat("Get users list is not null", users.getElements(), notNullValue()); assertThat("Get users list is not empty", !users.getElements().isEmpty()); assertThat("Get users items count coincide with list size", users.getElements().size(), equalTo(users.getTotalCount())); /* uncomment for additional output */ System.out.println(" >> Get users result: " + users.toString()); // test identity provider (IdP) get user by username User user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())) .queryParam("plain", true).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username result is not null", user2, notNullValue()); assertThat("Get user by username coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by username result: " + user2.toString()); // test identity provider (IdP) get user by email address user2 = target.path(path.value()).path(user.getEmail()).queryParam("use_email", true) .queryParam("plain", true).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by email address result is not null", user2, notNullValue()); assertThat("Get user by email address coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by email address result: " + user2.toString()); // test identity provider (IdP) update user user.setPassword("updated_password2"); response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)) .put(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Update user response is not null", response3, notNullValue()); assertThat("Update user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("Update user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Update user response entity is not null", payload, notNullValue()); assertThat("Update user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Update user response body (JSON), empty is OK: " + payload); System.out.println(" >> Update user response JAX-RS object: " + response3); System.out.println(" >> Update user HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get user by username after update user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username after update result is not null", user2, notNullValue()); assertThat("Get user by username after update coincides with expected", user2.equalsIgnoringVolatile(user)); /* uncomment for additional output */ System.out.println(" >> Get user by username after update result: " + user2.toString()); // test identity provider (IdP) get user by username with revoked token try { target.path(path.value()).path(toResourceOwnerId(user.getUserid())) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2)).get(User.class); fail("Should have thrown an NotAuthorizedException because access token is revoked"); } catch (NotAuthorizedException e) { assertThat(e.getMessage(), containsString("HTTP 401 Unauthorized")); } // test identity provider (IdP) delete user response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).delete(); assertThat("Delete user response is not null", response3, notNullValue()); assertThat("Delete user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("Delete user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Delete user response entity is not null", payload, notNullValue()); assertThat("Delete user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Delete user response body (JSON), empty is OK: " + payload); System.out.println(" >> Delete user response JAX-RS object: " + response3); System.out.println(" >> Delete user HTTP headers: " + response3.getStringHeaders()); // test user registration path = UserRegistration.class.getAnnotation(Path.class); System.out.println( " >> User registration resource server: " + target.path(path.value()).getUri().toString()); response3 = target.path(path.value()).queryParam("skip_activation", true).request() .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Create pending user response is not null", response3, notNullValue()); assertThat("Create pending user response is CREATED", response3.getStatus(), equalTo(CREATED.getStatusCode())); assertThat("Create pending user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Create pending user response entity is not null", payload, notNullValue()); assertThat("Create pending user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Create pending user response body (JSON), empty is OK: " + payload); System.out.println(" >> Create pending user response JAX-RS object: " + response3); System.out.println(" >> Create pending user HTTP headers: " + response3.getStringHeaders()); // test user registration new user activation final PendingUser pendingUser = PENDING_USER_DAO.findByEmail(user.getEmail()); final PendingUser pendingUser2 = PendingUser.builder() .user(User.builder().email(user.getEmail()).build()) .activationCode(pendingUser.getActivationCode()).build(); response3 = target.path(path.value()).path(user.getEmail()).request() .put(Entity.entity(pendingUser2, MediaType.APPLICATION_JSON_TYPE)); assertThat("New user activation response is not null", response3, notNullValue()); assertThat("New user activation response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("New user activation response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("New user activation response entity is not null", payload, notNullValue()); assertThat("New user activation response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> New user activation response body (JSON), empty is OK: " + payload); System.out.println(" >> New user activation response JAX-RS object: " + response3); System.out.println(" >> New user activation HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get user by username after activation path = IdentityProvider.class.getAnnotation(Path.class); System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString()); user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username after validation result is not null", user2, notNullValue()); assertThat("Get user by username after validation permissions are not null", user2.getPermissions(), notNullValue()); assertThat("Get user by username after validation permissions are not empty", !user2.getPermissions().isEmpty()); assertThat("Get user by username after validation coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by username after validation result: " + user2.toString()); // test check user availability with form field: username, expected response: user unavailable path = UserRegistration.class.getAnnotation(Path.class); final Path innerPath = UserRegistration.class .getMethod("checkUserAvailability", new Class<?>[] { MultivaluedMap.class }) .getAnnotation(Path.class); System.out.println(" >> Check user availability: " + target.path(path.value()).path(innerPath.value()).getUri().toString()); form = new Form(); form.param("type", "username"); form.param("username", user.getUserid()); response3 = target.path(path.value()).path(innerPath.value()).request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED)); assertThat("Check user availability response is not null", response3, notNullValue()); assertThat("Check user availability response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Check user availability response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Check user availability response entity is not null", payload, notNullValue()); assertThat("Check user availability response entity is not empty", !isBlank(payload)); assertThat("Check user availability coincides with expected", !readValid(payload)); /* uncomment for additional output */ System.out.println(" >> Check user availability response body (JSON): " + payload); System.out.println(" >> Check user availability response JAX-RS object: " + response3); // test check user availability with form field: email, expected response: user available (using plain REST, no Jersey client) uri = target.path(path.value()).path(innerPath.value()).getUri(); System.out.println(" >> Check user availability (plain): " + uri.toString()); final String response4 = Request.Post(uri).addHeader("Accept", "text/javascript") // also supports: application/json .bodyForm(form().add("email", "not_existing_email@example.org").add("type", "email").build()) .execute().returnContent().asString(); assertThat("Check user availability (plain) is not null", response4, notNullValue()); assertThat("Check user availability (plain) is not empty", isNotBlank(response4)); /* uncomment for additional output */ System.out.println("Check user availability (plain): " + response4); final boolean valid = readValid(response4); assertThat("Check user availability (plain) concides with expected", valid, equalTo(true)); /* uncomment for additional output */ System.out.println("Check user availability (plain) returns: " + valid); } catch (Exception e) { e.printStackTrace(System.err); fail("AuthTest.test() failed: " + e.getMessage()); } finally { System.out.println("AuthTest.test() has finished"); } }
From source file:org.apache.sling.distribution.transport.impl.SimpleHttpDistributionTransport.java
public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage, @Nonnull DistributionTransportContext distributionContext) throws DistributionException { String hostAndPort = getHostAndPort(distributionEndpoint.getUri()); DistributionPackageInfo info = distributionPackage.getInfo(); URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class); if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) { log.debug("skipping distribution of package {}to same origin {}", distributionPackage.getId(), hostAndPort);//from w w w .j a v a 2 s . c o m } else { try { Executor executor = getExecutor(distributionContext); Request req = Request.Post(distributionEndpoint.getUri()).useExpectContinue(); // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2 if (distributionPackage instanceof AbstractDistributionPackage) { AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage; if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) { req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage())); } } InputStream inputStream = null; try { inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage); req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); Response response = executor.execute(req); response.returnContent(); // throws an error if HTTP status is >= 300 } finally { IOUtils.closeQuietly(inputStream); } log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri()); } catch (HttpHostConnectException e) { throw new RecoverableDistributionException( "endpoint not available " + distributionEndpoint.getUri(), e); } catch (HttpResponseException e) { int statusCode = e.getStatusCode(); if (statusCode == 404 || statusCode == 401) { throw new RecoverableDistributionException( "not enough rights for " + distributionEndpoint.getUri(), e); } throw new DistributionException(e); } catch (Exception e) { throw new DistributionException(e); } } }
From source file:org.eclipse.epp.internal.logging.aeri.ui.v2.AeriServer.java
public ServerResponse upload(ErrorReport report, IProgressMonitor monitor) throws IOException { String body = Reports.toJson(report, false); StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_OCTET_STREAM.withCharset(UTF_8)); // length of zipped conent is unknown, using the progress of the string-stream instead. // download progress percentage will be accurate, download progress size will be too large by the compression factor HttpEntity entity = new GzipCompressingEntity( Responses.decorateForProgressMonitoring(stringEntity, monitor)); String submitUrl = configuration.getSubmitUrl(); URI target = newURI(submitUrl); // @formatter:off Request request = Request.Post(target).viaProxy(getProxyHost(target).orNull()).body(entity) .connectTimeout(configuration.getConnectTimeoutMs()).staleConnectionCheck(true) .socketTimeout(configuration.getSocketTimeoutMs()); // @formatter:on String response = proxyAuthentication(executor, target).execute(request).returnContent().asString(); ServerResponse05 response05 = Json.deserialize(response, ServerResponse05.class); // TODO complete dto ServerResponse result = new ServerResponse(); result.setReportTitle(abbreviate(report.getStatus().getMessage(), 80)); result.setIncidentId(response05.getBugId().orNull()); result.setIncidentUrl(response05.getBugUrl().orNull()); result.setResolution(tryParse(response05)); result.setCommitterMessage(response05.getInformation().orNull()); return result; }
From source file:org.talend.components.datastewardship.connection.TdsConnection.java
/** * Executes Http Post request/* w w w . j a v a 2 s. c o m*/ * * @param resource REST API resource. E. g. issue/{issueId} * @param body message body * @return response status code * @throws ClientProtocolException * @throws IOException */ public int post(String resource, String body) throws IOException { Request post = Request.Post(hostPort + resource).addHeader(authorization).bodyString(body, contentType); return executor.execute(post).returnResponse().getStatusLine().getStatusCode(); }
From source file:org.talend.components.jira.connection.Rest.java
/** * Executes Http Post request/*from w ww .ja v a2s. c o m*/ * * @param resource REST API resource. E. g. issue/{issueId} * @param body message body * @return response status code * @throws ClientProtocolException * @throws IOException */ public int post(String resource, String body) throws IOException { Request post = Request.Post(hostPort + resource).bodyString(body, contentType); for (Header header : headers) { post.addHeader(header); } executor.clearCookies(); return executor.execute(post).returnResponse().getStatusLine().getStatusCode(); }
From source file:org.usc.wechat.mp.sdk.util.HttpUtil.java
public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Object requestBody, Class<T> jsonRtnClazz) { if (request == null || license == null || requestBody == null || jsonRtnClazz == null) { return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "missing post request params"); }/*from w w w.j av a2 s. c om*/ String requestUrl = request.getUrl(); String requestName = request.getName(); List<NameValuePair> nameValuePairs = buildNameValuePairs(license, paramMap); String body = JSONObject.toJSONString(requestBody); URI uri = buildURI(requestUrl, nameValuePairs); if (uri == null) { return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "build request URI failed"); } try { String rtnJson = Request.Post(uri).connectTimeout(CONNECT_TIMEOUT).socketTimeout(SOCKET_TIMEOUT) .bodyString(body, ContentType.create("text/html", Consts.UTF_8)).execute() .handleResponse(HttpUtil.UTF8_CONTENT_HANDLER); T jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, jsonRtnClazz); log.info(requestName + " result:\n url={},\n body={},\n rtn={},\n {}", uri, body, rtnJson, jsonRtn); return jsonRtn; } catch (Exception e) { String msg = requestName + " failed:\n url=" + uri + ",\n body=" + body; log.error(msg, e); return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "post request server failed"); } }