Java Code Examples for org.apache.http.client.methods.HttpPost#setEntity()
The following examples show how to use
org.apache.http.client.methods.HttpPost#setEntity() .
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: CxfWsCdiSecureExampleTest.java From wildfly-camel-examples with Apache License 2.0 | 6 votes |
@Test public void ui() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpPost request = new HttpPost(UI_URI); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setEntity(new StringEntity("message=Hello&name=Kermit", StandardCharsets.UTF_8)); try (CloseableHttpResponse response = httpclient.execute(request)) { Assert.assertEquals(200, response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, StandardCharsets.UTF_8); Assert.assertTrue(body.contains("Hello Kermit")); } } }
Example 2
Source File: HistoricTaskInstanceQueryResourceTest.java From activiti6-boot2 with Apache License 2.0 | 6 votes |
protected void assertResultsPresentInPostDataResponse(String url, ObjectNode body, int numberOfResultsExpected, String... expectedTaskIds) throws JsonProcessingException, IOException { // Do the actual call HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + url); httpPost.setEntity(new StringEntity(body.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_OK); JsonNode dataNode = objectMapper.readTree(response.getEntity().getContent()).get("data"); closeResponse(response); assertEquals(numberOfResultsExpected, dataNode.size()); // Check presence of ID's if (expectedTaskIds != null) { List<String> toBeFound = new ArrayList<String>(Arrays.asList(expectedTaskIds)); Iterator<JsonNode> it = dataNode.iterator(); while (it.hasNext()) { String id = it.next().get("id").textValue(); toBeFound.remove(id); } assertTrue("Not all entries have been found in result, missing: " + StringUtils.join(toBeFound, ", "), toBeFound.isEmpty()); } }
Example 3
Source File: JenkinsHttpClient.java From jenkins-client-java with MIT License | 6 votes |
/** * Post a text entity to the given URL with the given content type * * @param path The path. * @param textData The data. * @param contentType {@link ContentType} * @param crumbFlag true or false. * @return resulting response * @throws IOException in case of an error. */ @Override public String postText(String path, String textData, ContentType contentType, boolean crumbFlag) throws IOException { HttpPost request = new HttpPost(UrlUtils.toJsonApiUri(uri, context, path)); if (crumbFlag == true) { Crumb crumb = get("/crumbIssuer", Crumb.class); if (crumb != null) { request.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb())); } } if (textData != null) { request.setEntity(new StringEntity(textData, contentType)); } HttpResponse response = client.execute(request, localContext); jenkinsVersion = ResponseUtils.getJenkinsVersion(response); try { httpResponseValidator.validateResponse(response); return IOUtils.toString(response.getEntity().getContent()); } finally { EntityUtils.consume(response.getEntity()); releaseConnection(request); } }
Example 4
Source File: RestClient.java From kylin with Apache License 2.0 | 6 votes |
public void clearCacheForCubeMigration(String cube, String project, String model, Map<String, String> tableToProjects) throws IOException { String url = baseUrl + "/cache/migration"; HttpPost post = new HttpPost(url); post.addHeader("Accept", "application/json, text/plain, */*"); post.addHeader("Content-Type", APPLICATION_JSON); HashMap<String, Object> paraMap = new HashMap<String, Object>(); paraMap.put("cube", cube); paraMap.put("project", project); paraMap.put("model", model); paraMap.put("tableToProjects", tableToProjects); String jsonMsg = JsonUtil.writeValueAsString(paraMap); post.setEntity(new StringEntity(jsonMsg, UTF_8)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException(INVALID_RESPONSE + response.getStatusLine().getStatusCode()); } }
Example 5
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testMutipleAcceptHeader() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/booksplain"; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(endpointAddress); post.addHeader("Content-Type", "text/plain"); post.addHeader("Accept", "text/xml"); post.addHeader("Accept", "text/plain"); post.setEntity(new StringEntity("12345")); try { CloseableHttpResponse response = client.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(EntityUtils.toString(response.getEntity()), "12345"); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example 6
Source File: JAXRSClientServerBookTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testNoMessageReaderFound() throws Exception { String endpointAddress = "http://localhost:" + PORT + "/bookstore/binarybooks"; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(endpointAddress); post.addHeader("Content-Type", "application/octet-stream"); post.addHeader("Accept", "text/xml"); post.setEntity(new StringEntity("Bar")); try { CloseableHttpResponse response = client.execute(post); assertEquals(415, response.getStatusLine().getStatusCode()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example 7
Source File: EngineRule.java From camunda-external-task-client-java with Apache License 2.0 | 6 votes |
protected HttpPost createDeploymentRequest(String tenantId, BpmnModelInstance... processes) { String uri = String.format(URI_DEPLOYMEN_CREATE, getEngineUrl()); HttpPost post = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create() .addTextBody("deployment-name", "deployment") .addTextBody("enable-duplicate-filtering", "false") .addTextBody("deployment-source", "process application"); if (tenantId != null) { builder.addTextBody("tenant-id", tenantId); } for (int i = 0; i < processes.length; i++) { BpmnModelInstance process = processes[i]; String processAsString = Bpmn.convertToString(process); builder.addBinaryBody( String.format("data %d", i), processAsString.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM, String.format("test%d.bpmn", i)); } HttpEntity entity = builder.build(); post.setEntity(entity); return post; }
Example 8
Source File: HttpUtils.java From lorne_core with Apache License 2.0 | 5 votes |
public static String post(String url, List<PostParam> params) { CloseableHttpClient httpClient = HttpClientFactory.createHttpClient(); HttpPost request = new HttpPost(url); if (params != null) { List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size()); for (PostParam param : params) { NameValuePair pair = new BasicNameValuePair(param.getName(), param.getValue()); pairList.add(pair); } request.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); } return execute(httpClient, request); }
Example 9
Source File: CouchbaseWriterTest.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Implement the equivalent of: * curl -XPOST -u Administrator:password localhost:httpPort/pools/default/buckets \ -d bucketType=couchbase \ * -d name={@param bucketName} -d authType=sasl -d ramQuotaMB=200 **/ private boolean createBucket(String bucketName) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try { HttpPost httpPost = new HttpPost("http://localhost:" + _couchbaseTestServer.getPort() + "/pools/default/buckets"); List<NameValuePair> params = new ArrayList<>(2); params.add(new BasicNameValuePair("bucketType", "couchbase")); params.add(new BasicNameValuePair("name", bucketName)); params.add(new BasicNameValuePair("authType", "sasl")); params.add(new BasicNameValuePair("ramQuotaMB", "200")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //Execute and get the response. HttpResponse response = httpClient.execute(httpPost); log.info(String.valueOf(response.getStatusLine().getStatusCode())); return true; } catch (Exception e) { log.error("Failed to create bucket {}", bucketName, e); return false; } }
Example 10
Source File: MutualTLSClientTest.java From keycloak with Apache License 2.0 | 5 votes |
private OAuthClient.AccessTokenResponse getAccessTokenResponseWithQueryParams(String clientId, CloseableHttpClient client) throws Exception { OAuthClient.AccessTokenResponse token;// This is a very simplified version of HttpPost post = new HttpPost(oauth.getAccessTokenUrl() + "?client_id=" + clientId); List<NameValuePair> parameters = new LinkedList<>(); parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE)); parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, oauth.getCurrentQuery().get(OAuth2Constants.CODE))); parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri())); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, Charsets.UTF_8); post.setEntity(formEntity); return new OAuthClient.AccessTokenResponse(client.execute(post)); }
Example 11
Source File: GenesisService.java From chatbot with Apache License 2.0 | 5 votes |
private String makeRequest(String endpoint, String uri, String requestType) { try { HttpPost httpPost = new HttpPost(endpoint); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("url", uri)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); String result = null; String entities = EntityUtils.toString(response.getEntity()); JsonNode rootNode = new ObjectMapper().readTree(entities).get(requestType); switch (requestType) { case "similarEntities": case "relatedEntities": int count = 0; result = ""; for (JsonNode node : rootNode) { count++; if (count <= ResponseData.MAX_DATA_SIZE) { result += "<" + node.get("url").getTextValue() + "> "; } else { break; } } break; case "summary": result = rootNode.getTextValue(); break; } return result.trim(); } catch (Exception e) { e.printStackTrace(); } return null; }
Example 12
Source File: HttpClientUtil.java From ueboot with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 使用post方式提交参数 * * @param url url * @param params 提交的参数已key,value的形式保存在map当中 * @param socketTime 链接超时时间 * @param connectTimeout 链接超时时间 * @param charset 字符集 * @return 返回值 * @throws ClientProtocolException ClientProtocolException * @throws IOException IOException */ public static String post(String url, Map<String, String> params, int socketTime, int connectTimeout, String charset) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(socketTime <= 0 ? 120000 : socketTime) .setConnectTimeout(connectTimeout <= 0 ? 120000 : connectTimeout) .setConnectionRequestTimeout(connectTimeout <= 0 ? 120000 : connectTimeout) .build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } if (StringUtils.isEmpty(charset)) { charset = CHARSET; } httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset)); CloseableHttpResponse response1 = null; try { response1 = httpclient.execute(httpPost); HttpEntity entity1 = response1.getEntity(); String responseBody = EntityUtils.toString(entity1, charset); EntityUtils.consume(entity1); StatusLine statusLine = response1.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.info("statusCode:{}", statusCode); if (statusCode != 200) { writeLog(statusCode, responseBody); } return responseBody; } finally { IOUtils.closeQuietly(response1); } }
Example 13
Source File: HttpClientUtil.java From charging_pile_cloud with MIT License | 5 votes |
/** * 封装HTTP POST方法 * * @param * @param * @return * @throws Exception */ public static String post(String url, Map<String, String> paramMap) throws Exception { @SuppressWarnings("resource") HttpClient httpClient = new CertificateAuthorityHttpClientUtil(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> formparams = setHttpParams(paramMap); UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8"); httpPost.setEntity(param); HttpResponse response = httpClient.execute(httpPost); String httpEntityContent = getHttpEntityContent(response); httpPost.abort(); return httpEntityContent; }
Example 14
Source File: PropertyIntegrationForceHttpContentLengthPropertyTestCase.java From product-ei with Apache License 2.0 | 5 votes |
@Test(groups = "wso2.esb", description = "Tests when both properties are disabled", dependsOnMethods = "testWithEnableFORCE_HTTP_CONTENT_LENGTHAndCOPY_CONTENT_LENGTH_FROM_INCOMINGTest") public void testWithDisableFORCE_HTTP_CONTENT_LENGTHAndCOPY_CONTENT_LENGTH_FROM_INCOMINGTest () throws Exception { loadESBConfigurationFromClasspath ("/artifacts/ESB/mediatorconfig/property/DisableFORCE_HTTP_CONTENT_LENGTH.xml"); wireServer.start(); HttpClient httpclient = new DefaultHttpClient(); StringEntity strEntity = new StringEntity("<soapenv:Envelope xmlns:soapenv=\"http://schemas." + "xmlsoap.org/soap/envelope/\" xmlns:ser=\"" + "http://services.samples\" xmlns:xsd=\"" + "http://services.samples/xsd\">\n" + " <soapenv:Header/>\n" + " <soapenv:Body>\n" + " <ser:getQuote>\n" + " <!--Optional:-->\n" + " <ser:request>\n" + " <!--Optional:-->\n" + " <xsd:symbol>WSO2</xsd:symbol>\n" + " </ser:request>\n" + " </ser:getQuote>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>", "text/xml", "UTF-8"); HttpPost post = new HttpPost(getProxyServiceURLHttp("FORCE_HTTP_CONTENT_LENGTH_FalseTestProxy")); post.setHeader("SOAPAction","urn:getQuote"); post.setEntity(strEntity); // Execute request httpclient.execute(post); assertFalse(wireServer.getCapturedMessage().contains("Content-Length"), "Content-Length found in the out-going message"); }
Example 15
Source File: RequestProcessor.java From cellery-distribution with Apache License 2.0 | 5 votes |
/** * Execute http post request * * @param url url * @param contentType content type * @param acceptType accept type * @param authHeader authorization header * @param payload post payload * @return Closable http response * @throws APIException Api exception when an error occurred */ public String doPost(String url, String contentType, String acceptType, String authHeader, String payload) throws APIException { String returnObj = null; try { if (log.isDebugEnabled()) { log.debug("Post payload: " + payload); log.debug("Post auth header: " + authHeader); } StringEntity payloadEntity = new StringEntity(payload); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(Constants.Utils.HTTP_CONTENT_TYPE, contentType); httpPost.setHeader(Constants.Utils.HTTP_RESPONSE_TYPE_ACCEPT, acceptType); httpPost.setHeader(Constants.Utils.HTTP_REQ_HEADER_AUTHZ, authHeader); httpPost.setEntity(payloadEntity); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String responseStr = EntityUtils.toString(entity); int statusCode = response.getStatusLine().getStatusCode(); if (log.isDebugEnabled()) { log.debug("Response status code: " + statusCode); log.debug("Response string : " + responseStr); } if (responseValidate(statusCode, responseStr)) { returnObj = responseStr; } closeClientConnection(); } catch (IOException e) { String errorMessage = "Error occurred while executing the http Post connection."; log.error(errorMessage, e); throw new APIException(errorMessage, e); } return returnObj; }
Example 16
Source File: ElasticSearchRestClient.java From ingestion with Apache License 2.0 | 5 votes |
@Override public void execute() throws Exception { int statusCode = 0, triesCount = 0; HttpResponse response = null; String entity; synchronized (bulkBuilder) { entity = bulkBuilder.toString(); bulkBuilder = new StringBuilder(); } while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) { triesCount++; String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); logger.info("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) logger.debug("Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); } if (statusCode != HttpStatus.SC_OK) { if (response.getEntity() != null) { throw new EventDeliveryException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new EventDeliveryException("Elasticsearch status code was: " + statusCode); } } }
Example 17
Source File: NodeBbForumPoster.java From triplea with GNU General Public License v3.0 | 5 votes |
private String uploadSaveGame( final CloseableHttpClient client, final String token, final SaveGameParameter saveGame) throws IOException { final HttpPost fileUpload = new HttpPost(forumUrl + "/api/v2/util/upload"); fileUpload.setEntity( MultipartEntityBuilder.create() .addBinaryBody( "files[]", saveGame.path.toFile(), ContentType.APPLICATION_OCTET_STREAM, saveGame.displayName) .build()); HttpProxy.addProxy(fileUpload); addTokenHeader(fileUpload, token); try (CloseableHttpResponse response = client.execute(fileUpload)) { final int status = response.getStatusLine().getStatusCode(); if (status == HttpURLConnection.HTTP_OK) { final String json = EntityUtils.toString(response.getEntity()); final String url = (String) ((Map<?, ?>) ((List<?>) load.loadFromString(json)).get(0)).get("url"); return "\n[Savegame](" + url + ")"; } throw new IllegalStateException( "Failed to upload savegame, server returned Error Code " + status + "\nMessage:\n" + EntityUtils.toString(response.getEntity())); } }
Example 18
Source File: ContentItemCollectionResourceTest.java From flowable-engine with Apache License 2.0 | 4 votes |
public void testCreateContentItem() throws Exception { ContentItem urlContentItem = null; try { ObjectNode requestNode = objectMapper.createObjectNode(); requestNode.put("name", "Simple content item"); requestNode.put("mimeType", "application/pdf"); requestNode.put("taskId", "12345"); requestNode.put("processInstanceId", "123456"); requestNode.put("contentStoreId", "id"); requestNode.put("contentStoreName", "testStore"); requestNode.put("createdBy", "testa"); requestNode.put("lastModifiedBy", "testb"); HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + ContentRestUrls.createRelativeResourceUrl( ContentRestUrls.URL_CONTENT_ITEM_COLLECTION)); httpPost.setEntity(new StringEntity(requestNode.toString())); CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED); // Check if content item is created List<ContentItem> contentItems = contentService.createContentItemQuery().list(); assertThat(contentItems).hasSize(1); urlContentItem = contentItems.get(0); JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent()); closeResponse(response); assertThatJson(responseNode) .when(Option.IGNORING_EXTRA_FIELDS) .isEqualTo("{" + " id: '" + urlContentItem.getId() + "'," + " name: 'Simple content item'," + " mimeType: 'application/pdf'," + " taskId: '12345'," + " processInstanceId: '123456'," + " contentStoreId: 'id'," + " contentStoreName: 'testStore'," + " contentAvailable: false," + " created: " + new TextNode(getISODateStringWithTZ(urlContentItem.getCreated())) + "," + " createdBy: 'testa'," + " lastModified: " + new TextNode(getISODateStringWithTZ(urlContentItem.getLastModified())) + "," + " lastModifiedBy: 'testb'," + " url: '" + SERVER_URL_PREFIX + ContentRestUrls.createRelativeResourceUrl( ContentRestUrls.URL_CONTENT_ITEM, urlContentItem.getId()) + "'" + "}"); } finally { if (urlContentItem != null) { contentService.deleteContentItem(urlContentItem.getId()); } } }
Example 19
Source File: BasicHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 4 votes |
public void setPostEntity(String data, File file, HttpPost httppost) { final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addTextBody("body", data, ContentType.APPLICATION_XML); httppost.setEntity(builder.build()); }
Example 20
Source File: SikuliExtensionServletTest.java From selenium-grid-extensions with Apache License 2.0 | 4 votes |
@Test public void shouldReturnErrorInformation() throws IOException { String invocationJsonString = failingInvocationJsonString(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost request = new HttpPost(basePath + "/" + URLEncoder.encode("mouse", "UTF-8")); request.setEntity(new StringEntity(invocationJsonString)); HttpResponse httpResponse = httpClient.execute(serverHost, request); int statusCode = httpResponse.getStatusLine().getStatusCode(); assertThat(statusCode, is(HttpStatus.SC_OK)); assertThat(EntityUtils.toString(httpResponse.getEntity()), containsString("notExistingMethod not found")); }