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; }
/** * 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 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()); }
HttpPost httpPost = null; URI encodedUri = getEncodingURI(url); httpPost = new HttpPost(encodedUri); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, DELIVER_CONN_TIMEOUT); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DELIVER_SOCKET_TIMEOUT); try { BasicNameValuePair basicNameValuePair = new BasicNameValuePair( key, value); nameValuePair.add(basicNameValuePair); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8)); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse != null) { int code = httpResponse.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { Log.d(TAG_LISTLOGIC, "post投递服务器返回200"); return; } else { httpPost.abort();
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()); } }
/** * post form */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (bodys != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); request.setEntity(formEntity); } return httpClient.execute(request); }
if(request instanceof HttpPostRequest) {//post HttpPostRequest post = (HttpPostRequest)request; reqObj = new HttpPost(post.getUrl()); NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue()); fields.add(nvp); HttpEntity entity = new UrlEncodedFormEntity(fields, "UTF-8"); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } catch (UnsupportedEncodingException e) { int status = response.getStatusLine().getStatusCode(); HttpResponse resp = new HttpResponse(); resp.setStatus(status); if(status == 302 || status == 301) { String redirectUrl = response.getFirstHeader("Location").getValue(); resp.setContent(UrlUtils.relative2Absolute(request.getUrl(), redirectUrl)); } else if(status == 200) { HttpEntity responseEntity = response.getEntity(); ByteArrayInputStream raw = toByteInputStream(responseEntity.getContent()); resp.setRaw(raw);
private boolean remoteUserExists(String[] user, String url) throws URISyntaxException, IOException, AuthenticationException { DefaultHttpClient authorizedClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = getPostParamsList(user); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = authorizedClient.execute(httpPost); EntityUtils.consume(response.getEntity()); int code = response.getStatusLine().getStatusCode(); return code != HttpURLConnection.HTTP_FORBIDDEN; }
try { HttpPost postRequest = new HttpPost(url); postRequest.addHeader(header.getKey(), header.getValue()); .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
HttpPost post = new HttpPost( uriBuilder.build() ); post.setHeader( CONTENT_TYPE, CONTENT_TYPE_TEXT_XML ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML ) ); post.setHeader( CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML String bodyParameterName = data.bodyParameters[ i ].getName(); String bodyParameterValue = data.inputRowMeta.getString( rowData, data.body_parameters_nrs[ i ] ); data.bodyParameters[ i ] = new BasicNameValuePair( bodyParameterName, bodyParameterValue ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.BodyValue", bodyParameterName, String queryParameterName = data.queryParameters[ i ].getName(); String queryParameterValue = data.inputRowMeta.getString( rowData, data.query_parameters_nrs[ i ] ); data.queryParameters[ i ] = new BasicNameValuePair( queryParameterName, queryParameterValue ); if ( isDebug() ) { logDebug( BaseMessages.getString( PKG, "HTTPPOST.Log.QueryValue", queryParameterName, post.setEntity( new UrlEncodedFormEntity( Arrays.asList( data.queryParameters ) ) );
private String post(String path, List<NameValuePair> nameValuePairs) { HttpPost post = new HttpPost(path); String result = null; try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = client.execute(post); logger.info("Status: {}", response.getStatusLine()); result = collectResponse(response); } catch (IOException e) { logger.error("While posting", e); } return result; }
protected void login() throws InterruptedException, IOException { PollingHttpClient defaultHttpClient = new PollingHttpClient(); HttpPost request = new HttpPost(getBaseUrl() + "/module/server/j_spring_security_check"); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", MOTECH)); nvps.add(new BasicNameValuePair("j_password", MOTECH)); request.setEntity(new UrlEncodedFormEntity(nvps, "UTF8")); HttpResponse response = defaultHttpClient.execute(request); assertEquals(String.format("Location: %s/module/server/home", getBaseUrl()), response.getFirstHeader("Location").toString()); assertFalse(response.getFirstHeader("Location").toString().contains("error=true")); }
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(); } }
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");
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); if (!authenticated) { String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity())); if (formAction == null) { formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
/** * 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()); }
public UrlEncodedFormEntity encodeForm( Map<?,?> params, Object contentType ) 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() ) ); } UrlEncodedFormEntity e = new UrlEncodedFormEntity( paramList, charset.name() ); if ( contentType != null ) e.setContentType( contentType.toString() ); return e; }
public void postData(final String email, final String password) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(LOGIN_URL); client.getParams().setParameter("http.useragent", "Custom Browser"); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email", email)); nameValuePairs.add(new BasicNameValuePair("password", password)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8); entity.setContentType("application/x-www-form-urlencoded"); post.setEntity(entity); printHeaders(client.execute(post)); printCookies(client.getCookieStore()); } catch (ClientProtocolException e) { LOG.error("ClientProtocolException", e); } catch (IOException e) { LOG.error("IOException", e); } }
} else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e);