List of usage examples for org.apache.http.client.methods HttpPost METHOD_NAME
String METHOD_NAME
To view the source code for org.apache.http.client.methods HttpPost METHOD_NAME.
Click Source Link
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.CustomApiClientTests.java
public void testInvokeTypedJsonObjectAsInput() throws Throwable { final JsonObject input = new JsonObject(); input.addProperty("firstName", "john"); input.addProperty("lastName", "doe"); input.addProperty("age", 30); MobileServiceClient client = null;/*from w w w. j ava 2 s . c o m*/ try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } client = client.withFilter(new EchoFilter()); try { PersonTestObject result = client .invokeApi("myApi", input, HttpPost.METHOD_NAME, null, PersonTestObject.class).get(); if (result == null) { fail("Expected one person result"); } else { assertEquals(input.get("firstName").getAsString(), result.getFirstName()); assertEquals(input.get("lastName").getAsString(), result.getLastName()); assertEquals(input.get("age").getAsInt(), result.getAge()); } } catch (Exception exception) { if (exception instanceof ExecutionException) { fail(exception.getCause().getMessage()); } else { fail(exception.getMessage()); } } }
From source file:com.azure.webapi.MobileServiceClient.java
/** * Invokes a custom API using POST HTTP method * /*w ww . j a va 2s. c om*/ * @param apiName * The API name * @param body * The json element to send as the request body * @param callback * The callback to invoke after the API execution */ public void invokeApi(String apiName, JsonElement body, ApiJsonOperationCallback callback) { invokeApi(apiName, body, HttpPost.METHOD_NAME, null, callback); }
From source file:org.elasticsearch.client.RequestConverters.java
static Request clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest) { String[] indices = clearIndicesCacheRequest.indices() == null ? Strings.EMPTY_ARRAY : clearIndicesCacheRequest.indices(); Request request = new Request(HttpPost.METHOD_NAME, endpoint(indices, "_cache/clear")); Params parameters = new Params(request); parameters.withIndicesOptions(clearIndicesCacheRequest.indicesOptions()); parameters.putParam("query", Boolean.toString(clearIndicesCacheRequest.queryCache())); parameters.putParam("fielddata", Boolean.toString(clearIndicesCacheRequest.fieldDataCache())); parameters.putParam("request", Boolean.toString(clearIndicesCacheRequest.requestCache())); parameters.putParam("fields", String.join(",", clearIndicesCacheRequest.fields())); return request; }
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testMultiGet() throws IOException { Map<String, String> expectedParams = new HashMap<>(); MultiGetRequest multiGetRequest = new MultiGetRequest(); if (randomBoolean()) { String preference = randomAlphaOfLength(4); multiGetRequest.preference(preference); expectedParams.put("preference", preference); }/*w w w .j av a 2s.co m*/ if (randomBoolean()) { multiGetRequest.realtime(randomBoolean()); if (multiGetRequest.realtime() == false) { expectedParams.put("realtime", "false"); } } if (randomBoolean()) { multiGetRequest.refresh(randomBoolean()); if (multiGetRequest.refresh()) { expectedParams.put("refresh", "true"); } } int numberOfRequests = randomIntBetween(0, 32); for (int i = 0; i < numberOfRequests; i++) { MultiGetRequest.Item item = new MultiGetRequest.Item(randomAlphaOfLength(4), randomAlphaOfLength(4), randomAlphaOfLength(4)); if (randomBoolean()) { item.routing(randomAlphaOfLength(4)); } if (randomBoolean()) { item.storedFields(generateRandomStringArray(16, 8, false)); } if (randomBoolean()) { item.version(randomNonNegativeLong()); } if (randomBoolean()) { item.versionType(randomFrom(VersionType.values())); } if (randomBoolean()) { randomizeFetchSourceContextParams(item::fetchSourceContext, new HashMap<>()); } multiGetRequest.add(item); } Request request = RequestConverters.multiGet(multiGetRequest); assertEquals(HttpPost.METHOD_NAME, request.getMethod()); assertEquals("/_mget", request.getEndpoint()); assertEquals(expectedParams, request.getParameters()); assertToXContentBody(multiGetRequest, request.getEntity()); }
From source file:org.elasticsearch.client.RequestConverters.java
static Request bulk(BulkRequest bulkRequest) throws IOException { Request request = new Request(HttpPost.METHOD_NAME, "/_bulk"); Params parameters = new Params(request); parameters.withTimeout(bulkRequest.timeout()); parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy()); // Bulk API only supports newline delimited JSON or Smile. Before executing // the bulk, we need to check that all requests have the same content-type // and this content-type is supported by the Bulk API. XContentType bulkContentType = null; for (int i = 0; i < bulkRequest.numberOfActions(); i++) { DocWriteRequest<?> action = bulkRequest.requests().get(i); DocWriteRequest.OpType opType = action.opType(); if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) { bulkContentType = enforceSameContentType((IndexRequest) action, bulkContentType); } else if (opType == DocWriteRequest.OpType.UPDATE) { UpdateRequest updateRequest = (UpdateRequest) action; if (updateRequest.doc() != null) { bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType); }/*from w w w. j a va 2 s .c om*/ if (updateRequest.upsertRequest() != null) { bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType); } } } if (bulkContentType == null) { bulkContentType = XContentType.JSON; } final byte separator = bulkContentType.xContent().streamSeparator(); final ContentType requestContentType = createContentType(bulkContentType); ByteArrayOutputStream content = new ByteArrayOutputStream(); for (DocWriteRequest<?> action : bulkRequest.requests()) { DocWriteRequest.OpType opType = action.opType(); try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) { metadata.startObject(); { metadata.startObject(opType.getLowercase()); if (Strings.hasLength(action.index())) { metadata.field("_index", action.index()); } if (Strings.hasLength(action.type())) { metadata.field("_type", action.type()); } if (Strings.hasLength(action.id())) { metadata.field("_id", action.id()); } if (Strings.hasLength(action.routing())) { metadata.field("routing", action.routing()); } if (action.version() != Versions.MATCH_ANY) { metadata.field("version", action.version()); } VersionType versionType = action.versionType(); if (versionType != VersionType.INTERNAL) { if (versionType == VersionType.EXTERNAL) { metadata.field("version_type", "external"); } else if (versionType == VersionType.EXTERNAL_GTE) { metadata.field("version_type", "external_gte"); } else if (versionType == VersionType.FORCE) { metadata.field("version_type", "force"); } } if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) { IndexRequest indexRequest = (IndexRequest) action; if (Strings.hasLength(indexRequest.getPipeline())) { metadata.field("pipeline", indexRequest.getPipeline()); } } else if (opType == DocWriteRequest.OpType.UPDATE) { UpdateRequest updateRequest = (UpdateRequest) action; if (updateRequest.retryOnConflict() > 0) { metadata.field("retry_on_conflict", updateRequest.retryOnConflict()); } if (updateRequest.fetchSource() != null) { metadata.field("_source", updateRequest.fetchSource()); } } metadata.endObject(); } metadata.endObject(); BytesRef metadataSource = BytesReference.bytes(metadata).toBytesRef(); content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length); content.write(separator); } BytesRef source = null; if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) { IndexRequest indexRequest = (IndexRequest) action; BytesReference indexSource = indexRequest.source(); XContentType indexXContentType = indexRequest.getContentType(); try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, indexSource, indexXContentType)) { try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) { builder.copyCurrentStructure(parser); source = BytesReference.bytes(builder).toBytesRef(); } } } else if (opType == DocWriteRequest.OpType.UPDATE) { source = XContentHelper.toXContent((UpdateRequest) action, bulkContentType, false).toBytesRef(); } if (source != null) { content.write(source.bytes, source.offset, source.length); content.write(separator); } } request.setEntity(new ByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType)); return request; }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.CustomApiClientTests.java
public void testInvokeTypedSingleString() throws Throwable { // Container to store callback's results and do the asserts. final ResultsContainer container = new ResultsContainer(); final String s = "Hello world"; MobileServiceClient client = null;//from ww w. java 2 s . c o m try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); client = client.withFilter(new EchoFilter()); String result = client.invokeApi("myApi", s, HttpPost.METHOD_NAME, null, String.class).get(); if (result == null) { container.setException(new Exception("Expected one string result")); } else { container.setCustomResult(result); } } catch (Exception exception) { container.setException(exception); } // Asserts Exception exception = container.getException(); if (exception != null) { fail(exception.getMessage()); } else { assertEquals(s, container.getCustomResult()); } }
From source file:org.elasticsearch.client.Request.java
static Request update(UpdateRequest updateRequest) throws IOException { String endpoint = endpoint(updateRequest.index(), updateRequest.type(), updateRequest.id(), "_update"); Params parameters = Params.builder(); parameters.withRouting(updateRequest.routing()); parameters.withParent(updateRequest.parent()); parameters.withTimeout(updateRequest.timeout()); parameters.withRefreshPolicy(updateRequest.getRefreshPolicy()); parameters.withWaitForActiveShards(updateRequest.waitForActiveShards()); parameters.withDocAsUpsert(updateRequest.docAsUpsert()); parameters.withFetchSourceContext(updateRequest.fetchSource()); parameters.withRetryOnConflict(updateRequest.retryOnConflict()); parameters.withVersion(updateRequest.version()); parameters.withVersionType(updateRequest.versionType()); // The Java API allows update requests with different content types // set for the partial document and the upsert document. This client // only accepts update requests that have the same content types set // for both doc and upsert. XContentType xContentType = null;//from w w w . ja v a2s . c om if (updateRequest.doc() != null) { xContentType = updateRequest.doc().getContentType(); } if (updateRequest.upsertRequest() != null) { XContentType upsertContentType = updateRequest.upsertRequest().getContentType(); if ((xContentType != null) && (xContentType != upsertContentType)) { throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + " and upsert [" + upsertContentType + "] documents"); } else { xContentType = upsertContentType; } } if (xContentType == null) { xContentType = Requests.INDEX_CONTENT_TYPE; } BytesRef source = XContentHelper.toXContent(updateRequest, xContentType, false).toBytesRef(); HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, ContentType.create(xContentType.mediaType())); return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), entity); }
From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java
/** * Returns the request that points to the backend service defined by the provided * <code>urlToService</code> URL. The headers of the origin request are copied to * the backend request, except of "host" and "content-length". * //from w w w. j av a 2s . c om * @param request * original request to the Web application * @param urlToService * URL to the targeted backend service * @return initialized backend service request * @throws IOException */ private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException { String method = request.getMethod(); LOGGER.debug("HTTP method: " + method); HttpRequestBase backendRequest = null; if (HttpPost.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPost post = new HttpPost(urlToService); post.setEntity(entity); backendRequest = post; } else if (HttpGet.METHOD_NAME.equals(method)) { HttpGet get = new HttpGet(urlToService); backendRequest = get; } else if (HttpPut.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPut put = new HttpPut(urlToService); put.setEntity(entity); backendRequest = put; } else if (HttpDelete.METHOD_NAME.equals(method)) { HttpDelete delete = new HttpDelete(urlToService); backendRequest = delete; } // copy headers from Web application request to backend request, while // filtering the blocked headers LOGGER.debug("backend request headers:"); Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS)); Enumeration<String> setCookieHeaders = request.getHeaders("Cookie"); while (setCookieHeaders.hasMoreElements()) { String cookieHeader = setCookieHeaders.nextElement(); if (blockedHeaders.contains(cookieHeader.toLowerCase())) { String replacedCookie = removeJSessionID(cookieHeader); backendRequest.addHeader("Cookie", replacedCookie); } LOGGER.debug("Cookie header => " + cookieHeader); } for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); if (!blockedHeaders.contains(headerName.toLowerCase())) { backendRequest.addHeader(headerName, request.getHeader(headerName)); LOGGER.debug(" => " + headerName + ": " + request.getHeader(headerName)); } else { LOGGER.debug(" => " + headerName + ": blocked request header"); } } return backendRequest; }
From source file:com.mirth.connect.client.core.ServerConnection.java
private HttpRequestBase createRequestBase(String method) { HttpRequestBase requestBase = null;//from w ww .ja v a 2s . c o m if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) { requestBase = new HttpGet(); } else if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) { requestBase = new HttpPost(); } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) { requestBase = new HttpPut(); } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) { requestBase = new HttpDelete(); } else if (StringUtils.equalsIgnoreCase(HttpOptions.METHOD_NAME, method)) { requestBase = new HttpOptions(); } else if (StringUtils.equalsIgnoreCase(HttpPatch.METHOD_NAME, method)) { requestBase = new HttpPatch(); } requestBase.setConfig(requestConfig); return requestBase; }
From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java
/** Builds the default request handlers **/ private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket, final Bucket ecsBucket) { final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER); // HEAD Object ///*from ww w .j a v a2 s .com*/ // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) { if (object.getKey().equals(objectName)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newObjectNotFoundError(request.getId(), objectName); })); // PUT Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String destBucketName = request.getParam("bucket"); final Bucket destBucket = buckets.get(destBucketName); if (destBucket == null) { return newBucketNotFoundError(request.getId(), destBucketName); } final String destObjectName = objectName(request.getParameters()); // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip" // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here. // // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html // String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length"); if (headerDecodedContentLength != null) { int contentLength = Integer.valueOf(headerDecodedContentLength); // Chunked requests have a payload like this: // // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8 // ... bytes of data .... // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4 // try (BufferedInputStream inputStream = new BufferedInputStream( new ByteArrayInputStream(request.getBody()))) { int b; // Moves to the end of the first signature line while ((b = inputStream.read()) != -1) { if (b == '\n') { break; } } final byte[] bytes = new byte[contentLength]; inputStream.read(bytes, 0, contentLength); destBucket.objects.put(destObjectName, bytes); return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } } return newInternalError(request.getId(), "Something is wrong with this PUT request"); })); // DELETE Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); bucket.objects.remove(objectName); return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); })); // GET Object // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}")) .forEach(path -> handlers.insert(path, (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } final String objectName = objectName(request.getParameters()); if (bucket.objects.containsKey(objectName)) { return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"), bucket.objects.get(objectName)); } return newObjectNotFoundError(request.getId(), objectName); })); // HEAD Bucket // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> { String bucket = request.getParam("bucket"); if (Strings.hasText(bucket) && buckets.containsKey(bucket)) { return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE); } else { return newBucketNotFoundError(request.getId(), bucket); } }); // GET Bucket (List Objects) Version 1 // // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> { final String bucketName = request.getParam("bucket"); final Bucket bucket = buckets.get(bucketName); if (bucket == null) { return newBucketNotFoundError(request.getId(), bucketName); } String prefix = request.getParam("prefix"); if (prefix == null) { prefix = request.getHeader("Prefix"); } return newListBucketResultResponse(request.getId(), bucket, prefix); }); // Delete Multiple Objects // // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> { final List<String> deletes = new ArrayList<>(); final List<String> errors = new ArrayList<>(); if (request.getParam("delete") != null) { // The request body is something like: // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete> String requestBody = Streams .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8)); if (requestBody.startsWith("<Delete>")) { final String startMarker = "<Key>"; final String endMarker = "</Key>"; int offset = 0; while (offset != -1) { offset = requestBody.indexOf(startMarker, offset); if (offset > 0) { int closingOffset = requestBody.indexOf(endMarker, offset); if (closingOffset != -1) { offset = offset + startMarker.length(); final String objectName = requestBody.substring(offset, closingOffset); boolean found = false; for (Bucket bucket : buckets.values()) { if (bucket.objects.containsKey(objectName)) { final Response authResponse = authenticateBucket(request, bucket); if (authResponse != null) { return authResponse; } bucket.objects.remove(objectName); found = true; } } if (found) { deletes.add(objectName); } else { errors.add(objectName); } } } } return newDeleteResultResponse(request.getId(), deletes, errors); } } return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request"); }); // non-authorized requests TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> { final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1)); final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \"" + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \"" + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\"" + "}"; final Map<String, String> headers = new HashMap<>(contentType("application/json")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }; // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"), (request) -> { final String response = EC2_PROFILE; final Map<String, String> headers = new HashMap<>(contentType("text/plain")); return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8)); }); // GET // // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html handlers.insert( nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"), (request) -> { final String profileName = request.getParam("profileName"); if (EC2_PROFILE.equals(profileName) == false) { return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(), "unknown profile".getBytes(UTF_8)); } return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token); }); // GET // // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"), (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token)); return handlers; }