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(); } }
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; }
/** * 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()); }
HttpPost httpPost = new HttpPost(config.getUrl()); try { httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8")); } catch (UnsupportedEncodingException e) { Log.warn("This systems doesn't support UTF-8!"); }
/** * 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; }
public static HttpResult httpPost(String url, List<String> headers, Map<String, String> paramValues, String encoding) { try { HttpPost httpost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).setMaxRedirects(5).build(); httpost.setConfig(requestConfig); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : paramValues.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); HttpResponse response = postClient.execute(httpost); HttpEntity entity = response.getEntity(); String charset = encoding; if (entity.getContentType() != null) { HeaderElement[] headerElements = entity.getContentType().getElements(); if (headerElements != null && headerElements.length > 0 && headerElements[0] != null && headerElements[0].getParameterByName("charset") != null) { charset = headerElements[0].getParameterByName("charset").getValue(); } } return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap()); } catch (Throwable e) { return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap()); } }
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 + ">>>"); }
pair("cm1", String.valueOf(parameters.getResultsCount())) ); final HttpPost post = new HttpPost(GA_ENDPOINT); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8); post.setEntity(entity); client.execute(post).close(); LOGGER.debug("GA done");
@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()); }
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 + "'"); } }
private String shortenLink(String applicationLink) { if (!LINK_PATTERN.matcher(applicationLink).matches()) { throw new IllegalArgumentException("Invalid link provided, must start with syncany:// and match link pattern."); } try { logger.log(Level.INFO, "Shortining link " + applicationLink + " via " + LINK_SHORT_API_URL_ADD + " ..."); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("l", applicationLink)); HttpPost postMethod = new HttpPost(LINK_SHORT_API_URL_ADD); postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse httpResponse = createHttpClient().execute(postMethod); ApplicationLinkShortenerResponse shortenerResponse = new Persister().read(ApplicationLinkShortenerResponse.class, httpResponse .getEntity().getContent()); return String.format(LINK_SHORT_URL_FORMAT, shortenerResponse.getShortLinkId()); } catch (Exception e) { logger.log(Level.WARNING, "Cannot shorten URL. Using long URL.", e); return applicationLink; } }
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; }
private static HttpPost buildPostMethod(final URI uri, final HttpCollectorAgent collectorAgent) { HttpPost method = new HttpPost(uri); List<NameValuePair> postParams = buildRequestParameters(collectorAgent); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8); method.setEntity(entity); return method; }
try { HttpPost postRequest = new HttpPost(url); .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity);
value = e.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(e.getKey(), value.toString())); entity = new UrlEncodedFormEntity(pairs, "UTF-8");
private static HttpPost buildPostMethod(final URI uri, final HttpCollectorAgent collectorAgent) { HttpPost method = new HttpPost(uri); List<NameValuePair> postParams = buildRequestParameters(collectorAgent); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8); method.setEntity(entity); return method; }
.setSocketTimeout(timeout) .build(); httpPost = new HttpPost(uri); List<NameValuePair> parameters = Lists.newArrayList(); for (String key : params.keySet()) { NameValuePair nameValuePair = new BasicNameValuePair(key, params.get(key)); parameters.add(nameValuePair); httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"))); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config);
pairs.add(new BasicNameValuePair("destination", baseUrl)); pairs.add(new BasicNameValuePair("username", username)); pairs.add(new BasicNameValuePair("password", password)); pairs.add(new BasicNameValuePair("flags", "0")); pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On")); pairs.add(new BasicNameValuePair("trusted", "0")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs); request.setEntity(formEntity);
private HttpPost buildPostResource(String resource, List<NameValuePair> queryParams, List<NameValuePair> formParams, Object... pathParams) throws UnsupportedEncodingException, URISyntaxException { URI uri = getUri(resource, queryParams, pathParams); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, ENCODING); HttpPost post = new HttpPost(uri); post.setEntity(entity); return post; }
.setSocketTimeout(timeout) .build(); httpPost = new HttpPost(uri); List<NameValuePair> parameters = Lists.newArrayList(); for (String key : params.keySet()) { NameValuePair nameValuePair = new BasicNameValuePair(key, params.get(key)); parameters.add(nameValuePair); httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"))); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config);