/** * Constructs a new {@link UrlEncodedFormEntity} with the list * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET} * * @param parameters list of name/value pairs * @throws UnsupportedEncodingException if the default encoding isn't supported */ public UrlEncodedFormEntity ( final List <? extends NameValuePair> parameters) throws UnsupportedEncodingException { super(URLEncodedUtils.format(parameters, HTTP.DEFAULT_CONTENT_CHARSET), HTTP.DEFAULT_CONTENT_CHARSET); setContentType(URLEncodedUtils.CONTENT_TYPE); }
public void postProperty(String url, String value) throws IOException { LOGGER.info("Posting property to the URL {}Property Value ={}", url, value); HttpPost post = httpClientFactory.createPost(url); CloseableHttpResponse response = null; try { post.setHeader("Confirm", "true"); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("value", value)))); response = execute(post); } finally { IOUtils.closeQuietly(response); post.releaseConnection(); } }
public void login(String username, String password) throws Exception { initHttpClient(); NameValue[] httpHeader = getHttpHeaders(); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("userId", username)); nvps.add(new BasicNameValuePair("userPassword", password)); log.debug("Making SOMFY http login call"); UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps); ByteArrayOutputStream bos = new ByteArrayOutputStream(); urlEncodedFormEntity.writeTo(bos); String body = bos.toString(); String response = httpClient.doHttpRequest(BASE_URL + "json/login",HttpPost.METHOD_NAME, "application/x-www-form-urlencoded", body,httpHeader); log.debug("Somfy login response <<<" + response + ">>>"); }
@Test public void shouldSetTheAcceptHeaderWhilePostingProperties() throws Exception { HttpPost post = mock(HttpPost.class); when(httpClientFactory.createPost("url")).thenReturn(post); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); when(httpClient.execute(post)).thenReturn(response); ArgumentCaptor<UrlEncodedFormEntity> entityCaptor = ArgumentCaptor.forClass(UrlEncodedFormEntity.class); service.postProperty("url", "value"); verify(post).setHeader("Confirm","true"); verify(post).setEntity(entityCaptor.capture()); UrlEncodedFormEntity expected = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("value", "value"))); UrlEncodedFormEntity actual = entityCaptor.getValue(); assertEquals(IOUtils.toString(expected.getContent()), IOUtils.toString(actual.getContent())); assertEquals(expected.getContentLength(), expected.getContentLength()); assertEquals(expected.getContentType(), expected.getContentType()); assertEquals(expected.getContentEncoding(), expected.getContentEncoding()); assertEquals(expected.isChunked(), expected.isChunked()); }
EntityBuilder entityBuilder = EntityBuilder.create() .setText(payload) .setContentType(requestContentType); entityBuilder.gzipCompress(); ((HttpEntityEnclosingRequest) httpUriRequest).setEntity(entityBuilder.build());
/** * Set the request body as a url-encoded list of parameters. This is * typically used to simulate a HTTP form POST. * For multi-valued parameters, enclose the values in a list, e.g. * <pre>[ key1 : ['val1', 'val2'], key2 : 'etc.' ]</pre> * * @param params * @return an {@link HttpEntity} encapsulating this request data * @throws UnsupportedEncodingException */ public UrlEncodedFormEntity encodeForm(Map<?, ?> params) throws UnsupportedEncodingException { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (Object key : params.keySet()) { Object val = params.get(key); if (val instanceof List) for (Object subVal : (List) val) paramList.add(new BasicNameValuePair(key.toString(), (subVal == null) ? "" : subVal.toString())); else paramList.add(new BasicNameValuePair(key.toString(), (val == null) ? "" : val.toString())); } return new UrlEncodedFormEntity(paramList, encoderConfig.defaultContentCharset()); }
EntityBuilder entityBuilder = EntityBuilder.create() .setText(payload) .setContentType(requestContentType); entityBuilder.gzipCompress(); ((HttpEntityEnclosingRequest) httpUriRequest).setEntity(entityBuilder.build());
/** * Constructs a new {@link UrlEncodedFormEntity} with the list * of parameters in the specified encoding. * * @param parameters list of name/value pairs * @param encoding encoding the name/value pairs be encoded with * @throws UnsupportedEncodingException if the encoding isn't supported */ public UrlEncodedFormEntity ( final List <? extends NameValuePair> parameters, final String encoding) throws UnsupportedEncodingException { super(URLEncodedUtils.format(parameters, encoding), encoding); setContentType(URLEncodedUtils.CONTENT_TYPE); }
/** * helper function to fill the request with header entries and posting body . */ private static HttpEntityEnclosingRequestBase completeRequest( final HttpEntityEnclosingRequestBase request, final List<Pair<String, String>> params) throws UnsupportedEncodingException { if (request != null) { if (null != params && !params.isEmpty()) { final List<NameValuePair> formParams = params.stream() .map(pair -> new BasicNameValuePair(pair.getFirst(), pair.getSecond())) .collect(Collectors.toList()); final HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8"); request.setEntity(entity); } } return request; }
@Test public void test() throws Exception { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpPut put = new HttpPut( String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER)); put.setEntity(EntityBuilder.create().setText(VALUE) .setContentType(ContentType.create("text-plain", StandardCharsets.UTF_8)).build()); try (CloseableHttpResponse resp = client.execute(put)) { assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode()); } HttpGet get = new HttpGet( String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER)); try (CloseableHttpResponse resp = client.execute(get)) { assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode()); assertEquals("value", Bytes.toString(ByteStreams.toByteArray(resp.getEntity().getContent()))); } get = new HttpGet(String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), "whatever", FAMILY, QUALIFIER)); try (CloseableHttpResponse resp = client.execute(get)) { assertEquals(HttpStatus.SC_NOT_FOUND, resp.getStatusLine().getStatusCode()); } } } }
private boolean httpPost(String url, String msg) { boolean ret = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpPost request = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("name", monitorName)); nvps.add(new BasicNameValuePair("msg", msg)); request.setEntity(new UrlEncodedFormEntity(nvps)); response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { LOG.info(EntityUtils.toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("Exception when sending http request to ali monitor", e); } finally { try { if (response != null) response.close(); httpClient.close(); } catch (Exception e) { LOG.error("Exception when closing httpclient", e); } } return ret; }
protected boolean populateHtmlFormCredential(HtmlFormCredential cred) { if (cred.getFormItems() == null || cred.getFormItems().size() <= 0) { logger.severe("No form items for " + curi); return false; } List<NameValuePair> formParams = new ArrayList<NameValuePair>(); for (Entry<String, String> n: cred.getFormItems().entrySet()) { formParams.add(new BasicNameValuePair(n.getKey(), n.getValue())); } // XXX should it get charset from somewhere? UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, HTTP.DEF_CONTENT_CHARSET); HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request; entityEnclosingRequest.setEntity(entity); return true; }
entity = new UrlEncodedFormEntity(pairs, "UTF-8");
nvps.add(new BasicNameValuePair(AzkabanClientParams.NAME, projectName)); nvps.add(new BasicNameValuePair(AzkabanClientParams.DESCRIPTION, description)); httpPost.setEntity(new UrlEncodedFormEntity(nvps));
/** * FORM authentication<br/> * Official Example: https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org * /apache/http/examples/client/ClientFormLogin.java */ private void doFormLogin(FormAuthInfo authInfo) { logger.info("FORM authentication for: {}", authInfo.getLoginTarget()); String fullUri = authInfo.getProtocol() + "://" + authInfo.getHost() + ":" + authInfo.getPort() + authInfo.getLoginTarget(); HttpPost httpPost = new HttpPost(fullUri); List<NameValuePair> formParams = new ArrayList<>(); formParams.add( new BasicNameValuePair(authInfo.getUsernameFormStr(), authInfo.getUsername())); formParams.add( new BasicNameValuePair(authInfo.getPasswordFormStr(), authInfo.getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); httpPost.setEntity(entity); try { httpClient.execute(httpPost); logger.debug("Successfully request to login in with user: {} to: {}", authInfo.getUsername(), authInfo.getHost()); } catch (ClientProtocolException e) { logger.error("While trying to login to: {} - Client protocol not supported", authInfo.getHost(), e); } catch (IOException e) { logger.error("While trying to login to: {} - Error making request", authInfo.getHost(), e); } }
protected HttpEntity buildPostRequestEntity(CrawlURI curi) { String enctype = (String) curi.getData().get(CoreAttributeConstants.A_SUBMIT_ENCTYPE); if (enctype == null) { enctype = ContentType.APPLICATION_FORM_URLENCODED.getMimeType(); } @SuppressWarnings("unchecked") List<NameValue> submitData = (List<NameValue>) curi.getData().get(CoreAttributeConstants.A_SUBMIT_DATA); if (enctype.equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { LinkedList<NameValuePair> nvps = new LinkedList<NameValuePair>(); for (NameValue nv: submitData) { nvps.add(new BasicNameValuePair(nv.name, nv.value)); } try { return new UrlEncodedFormEntity(nvps, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else if (enctype.equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValue nv: submitData) { entityBuilder.addTextBody(escapeForMultipart(nv.name), escapeForMultipart(nv.value)); } return entityBuilder.build(); } else { throw new IllegalStateException("unsupported form submission enctype='" + enctype + "'"); } }
} else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e);
/** * 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; } }
httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8")); } catch (UnsupportedEncodingException e) { Log.warn("This systems doesn't support UTF-8!"); }
); final HttpPost post = new HttpPost(GA_ENDPOINT); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8); post.setEntity(entity); client.execute(post).close();