org.apache.http.client.entity.UrlEncodedFormEntity Java Examples

The following examples show how to use org.apache.http.client.entity.UrlEncodedFormEntity. 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: MDSInterface2.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static MDSResult doPost(String scheme, String host, int port,
                                  String path,
                                  List<NameValuePair> postData) throws UnsupportedEncodingException {
    URI uri = null;
    try {
        uri = URIUtils.createURI(scheme, host, port, path, null, null);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(String.format("Can not post to mds: %s, %s, %d, %s", scheme, host, port, path), e);
    }
    Log.d(TAG, "doPost() uri: " + uri.toASCIIString());
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
    post.setEntity(entity);
    return MDSInterface2.doExecute(post);

}
 
Example #2
Source File: TaskControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testLaunchWithArguments() throws Exception {
	repository.save(new TaskDefinition("myTask3", "foo3"));
	this.registry.save("foo3", ApplicationType.task,
			"1.0.0", new URI("file:src/test/resources/apps/foo-task"), null);

	mockMvc.perform(post("/tasks/executions")
			// .param("name", "myTask3")
			.contentType(MediaType.APPLICATION_FORM_URLENCODED)
			.content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList(
					new BasicNameValuePair("name", "myTask3"),
					new BasicNameValuePair("arguments",
							"--foobar=jee --foobar2=jee2,foo=bar --foobar3='jee3 jee3'")))))
			.accept(MediaType.APPLICATION_JSON))
			.andDo(print())
			.andExpect(status().isCreated());

	ArgumentCaptor<AppDeploymentRequest> argumentCaptor = ArgumentCaptor.forClass(AppDeploymentRequest.class);
	verify(this.taskLauncher, atLeast(1)).launch(argumentCaptor.capture());

	AppDeploymentRequest request = argumentCaptor.getValue();
	assertThat(request.getCommandlineArguments().size(), is(3 + 2)); // +2 for spring.cloud.task.executionid and spring.cloud.data.flow.platformname
	// don't assume order in a list
	assertThat(request.getCommandlineArguments(), hasItems("--foobar=jee", "--foobar2=jee2,foo=bar", "--foobar3='jee3 jee3'"));
	assertEquals("myTask3", request.getDefinition().getProperties().get("spring.cloud.task.name"));
}
 
Example #3
Source File: RegistrationRecaptcha.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean validateRecaptcha(ValidationContext context, boolean success, String captcha, String secret) {
    HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient();
    HttpPost post = new HttpPost("https://www." + getRecaptchaDomain(context.getAuthenticatorConfig()) + "/recaptcha/api/siteverify");
    List<NameValuePair> formparams = new LinkedList<>();
    formparams.add(new BasicNameValuePair("secret", secret));
    formparams.add(new BasicNameValuePair("response", captcha));
    formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr()));
    try {
        UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(form);
        HttpResponse response = httpClient.execute(post);
        InputStream content = response.getEntity().getContent();
        try {
            Map json = JsonSerialization.readValue(content, Map.class);
            Object val = json.get("success");
            success = Boolean.TRUE.equals(val);
        } finally {
            content.close();
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.recaptchaFailed(e);
    }
    return success;
}
 
Example #4
Source File: HttpRemoteService.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private HttpPost createPost(String url, MultiValueMap<String, String> params) throws UnsupportedEncodingException {
    HttpPost post = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String key = entry.getKey();

        for (String value : entry.getValue()) {
            nvps.add(new BasicNameValuePair(key, value));
        }
    }

    post.setEntity(new UrlEncodedFormEntity(nvps));

    return post;
}
 
Example #5
Source File: TempletonDemo.java    From knox with Apache License 2.0 6 votes vote down vote up
private void demo( String url ) throws IOException {
  List<NameValuePair> parameters = new ArrayList<>();
  parameters.add( new BasicNameValuePair( "user.name", "hdfs" ) );
  parameters.add( new BasicNameValuePair( "jar", "wordcount/org.apache.hadoop-examples.jar" ) );
  parameters.add( new BasicNameValuePair( "class", "org.apache.org.apache.hadoop.examples.WordCount" ) );
  parameters.add( new BasicNameValuePair( "arg", "wordcount/input" ) );
  parameters.add( new BasicNameValuePair( "arg", "wordcount/output" ) );
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity( parameters, StandardCharsets.UTF_8 );
  HttpPost request = new HttpPost( url );
  request.setEntity( entity );

  HttpClientBuilder builder = HttpClientBuilder.create();
  CloseableHttpClient client = builder.build();
  HttpResponse response = client.execute( request );
  System.out.println( EntityUtils.toString( response.getEntity() ) );
}
 
Example #6
Source File: HttpUtil.java    From roncoo-education with MIT License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param param
 * @return
 */
public static String postForPay(String url, Map<String, Object> param) {
	logger.info("POST 请求, url={},map={}", url, param.toString());
	try {
		HttpPost httpPost = new HttpPost(url.trim());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> entry : param.entrySet()) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
		}
		StringEntity se = new UrlEncodedFormEntity(nvps, CHARSET_UTF_8);
		httpPost.setEntity(se);
		HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost);
		return EntityUtils.toString(httpResponse.getEntity(), CHARSET_UTF_8);
	} catch (Exception e) {
		logger.info("HTTP请求出错", e);
		e.printStackTrace();
	}
	return "";
}
 
Example #7
Source File: AgsClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Generates token.
 *
 * @param minutes expiration in minutes.
 * @param credentials credentials.
 * @return token response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public TokenResponse generateToken(int minutes, SimpleCredentials credentials) throws URISyntaxException, IOException {
  HttpPost post = new HttpPost(rootUrl.toURI().resolve("tokens/generateToken"));
  HashMap<String, String> params = new HashMap<>();
  params.put("f", "json");
  if (credentials != null) {
    params.put("username", StringUtils.trimToEmpty(credentials.getUserName()));
    params.put("password", StringUtils.trimToEmpty(credentials.getPassword()));
  }
  params.put("client", "requestip");
  params.put("expiration", Integer.toString(minutes));
  HttpEntity entity = new UrlEncodedFormEntity(params.entrySet().stream()
          .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()));
  post.setEntity(entity);

  try (CloseableHttpResponse httpResponse = httpClient.execute(post); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.readValue(responseContent, TokenResponse.class);
  }
}
 
Example #8
Source File: PastebinHandler.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
public String putInternal(String contents){
    HttpPost httppost = new HttpPost("http://pastebin.com/api/api_post.php");

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("api_dev_key", DEV_KEY));
    params.add(new BasicNameValuePair("api_paste_code", contents));
    params.add(new BasicNameValuePair("api_option", "paste"));
    if(isLoggedIn()) params.add(new BasicNameValuePair("api_user_key", userKey));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if(entity != null) {
            InputStream instream = entity.getContent();
            return IOUtils.toString(instream, "UTF-8");
        }

    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #9
Source File: AbstractHttpClient.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 根据请求信息创建HttpEntityEnclosingRequestBase.
 *
 * @param cls     类型Class
 * @param url     URL
 * @param headers Http请求头信息
 * @param params  请求参数列表
 * @return HttpEntityEnclosingRequestBase
 */
protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url,
                                                          final Map<String, String> headers, final Map<String, String> params) {
    try {
        final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url);
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> entityBase.addHeader(key, value));
        }

        final List<NameValuePair> pairs = covertParams2Nvps(params);
        entityBase.setEntity(new UrlEncodedFormEntity(pairs, this.conf.getCharset()));
        return entityBase;
    } catch (final Throwable e) {
        throw new HttpClientInvokeException(e.getMessage(), e);
    }
}
 
Example #10
Source File: ActionRunner.java    From curly with Apache License 2.0 6 votes vote down vote up
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException {
    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    List<NameValuePair> formParams = new ArrayList<>();
    postVariables.forEach((name, values) -> values.forEach(value -> {
        if (multipart) {
            if (value.startsWith("@")) {
                File f = new File(value.substring(1));
                multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName());
            } else {
                multipartBuilder.addTextBody(name, value);
            }
        } else {
            formParams.add(new BasicNameValuePair(name, value));
        }
    }));
    if (multipart) {
        request.setEntity(multipartBuilder.build());
    } else {
        request.setEntity(new UrlEncodedFormEntity(formParams));
    }
}
 
Example #11
Source File: LogoutAppServiceImpl.java    From web-sso with Apache License 2.0 6 votes vote down vote up
/**
 * 请求某个URL,带着参数列表。
 * @param url
 * @param nameValuePairs
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
protected String requestUrl(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException {
	HttpPost httpPost = new HttpPost(url);
	if(nameValuePairs!=null && nameValuePairs.size()>0){
		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	}
	CloseableHttpResponse response = httpClient.execute(httpPost);  
	try {  
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
			return content;
		}
		else{
			logger.warn("request the url: "+url+" , but return the status code is "+response.getStatusLine().getStatusCode());
			return null;
		}
	}
	finally{
		response.close();
	}
}
 
Example #12
Source File: MultipartBody.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the request payload.
 *
 * @return the payload containing the declared fields and files.
 */
public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;
                builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                builder.addPart(part.getKey(), new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #13
Source File: RESTSpewer.java    From extract with MIT License 6 votes vote down vote up
@Override
public void write(final TikaDocument tikaDocument) throws IOException {
	final HttpPut put = new HttpPut(uri.resolve(tikaDocument.getId()));
	final List<NameValuePair> params = new ArrayList<>();

	params.add(new BasicNameValuePair(fields.forId(), tikaDocument.getId()));
	params.add(new BasicNameValuePair(fields.forPath(), tikaDocument.getPath().toString()));
	params.add(new BasicNameValuePair(fields.forText(), toString(tikaDocument.getReader())));

	if (outputMetadata) {
		parametrizeMetadata(tikaDocument.getMetadata(), params);
	}

	put.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
	put(put);
}
 
Example #14
Source File: ProtocolTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Checks that the server accepts a formencoded POST with an update and a timeout parameter.
 */
@Test
public void testUpdateForm_POST() throws Exception {
	String update = "delete where { <monkey:pod> ?p ?o . }";
	String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL);
	CloseableHttpClient httpclient = HttpClients.createDefault();
	HttpPost post = new HttpPost(location);
	List<NameValuePair> nvps = new ArrayList<>();
	nvps.add(new BasicNameValuePair(Protocol.UPDATE_PARAM_NAME, update));
	nvps.add(new BasicNameValuePair(Protocol.TIMEOUT_PARAM_NAME, "1"));
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, Charsets.UTF_8);

	post.setEntity(entity);

	CloseableHttpResponse response = httpclient.execute(post);

	System.out.println("Update Form Post Status: " + response.getStatusLine());
	int statusCode = response.getStatusLine().getStatusCode();
	assertEquals(true, statusCode >= 200 && statusCode < 400);
}
 
Example #15
Source File: TestNNAnalyticsBase.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
@Test
public void testSQL1() throws IOException {
  HttpPost post = new HttpPost("http://localhost:4567/sql");
  List<NameValuePair> postParams = new ArrayList<>();
  postParams.add(
      new BasicNameValuePair("sqlStatement", "SELECT * FROM FILES WHERE fileSize = 0"));
  post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
  HttpResponse res = client.execute(hostPort, post);
  if (res.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
    List<String> text = IOUtils.readLines(res.getEntity().getContent());
    assertThat(text.size(), is(greaterThan(100)));
    assertThat(res.getStatusLine().getStatusCode(), is(HttpStatus.SC_OK));
  }
}
 
Example #16
Source File: HttpPostGet.java    From ApiManager with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String put(String path, Map<String, String> params, Map<String, String> headers) throws Exception {
    HttpPut method = new HttpPut(path);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000)
            .setConnectionRequestTimeout(3000).setStaleConnectionCheckEnabled(true).build();
    // 请求的参数信息传递
    List<NameValuePair> pairs = buildPairs(params);
    if (pairs.size() > 0) {
        HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
        method.setEntity(entity);
    }
    method.setConfig(requestConfig);
    return getResponse(method, headers);
}
 
Example #17
Source File: MultiController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private boolean emailPassword(String password, String username, String email) {
    HttpClient client = new DefaultHttpClient();
    try {
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
        HttpPost method = new HttpPost("http://subsonic.org/backend/sendMail.view");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("from", "[email protected]"));
        params.add(new BasicNameValuePair("to", email));
        params.add(new BasicNameValuePair("subject", "Subsonic Password"));
        params.add(new BasicNameValuePair("text",
                "Hi there!\n\n" +
                        "You have requested to reset your Subsonic password.  Please find your new login details below.\n\n" +
                        "Username: " + username + "\n" +
                        "Password: " + password + "\n\n" +
                        "--\n" +
                        "The Subsonic Team\n" +
                        "subsonic.org"));
        method.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
        client.execute(method);
        return true;
    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #18
Source File: FilePup.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private void initialize() throws Exception {
    httpPost = new NUHttpPost("http://www.filepup.net/link_upload.php");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("upload_file[]", "uploading.db"));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    httpPost.setEntity(entity);
    httpResponse = httpclient.execute(httpPost, httpContext);
    responseString = EntityUtils.toString(httpResponse.getEntity());
    uploadID = StringUtils.stringBetweenTwoStrings(responseString, "\"", "\",");
    uploadURL = "http://www.filepup.net/cgi-bin/upload.cgi?upload_id=" + uploadID;
}
 
Example #19
Source File: RemoteAdminService.java    From datawave with Apache License 2.0 5 votes vote down vote up
public ValidateVisibilityResponse validateVisibilities(String[] visibilities) {
    Preconditions.checkState(null != visibilities && visibilities.length > 0, "visibilities array cannot be null/empty");
    
    final List<NameValuePair> nvpList = new ArrayList<>();
    Arrays.stream(visibilities).forEach(s -> nvpList.add(new BasicNameValuePair("visibility", s)));
    final UrlEncodedFormEntity postBody = new UrlEncodedFormEntity(nvpList::iterator);
    
    // @formatter:off
    return execPost(
        Suffix.VALIDATE_VIZ.get(),
        readers.get(Suffix.VALIDATE_VIZ),
        postBody,
        () -> Suffix.VALIDATE_VIZ.get() + ": " + Arrays.toString(visibilities));
    // @formatter:on
}
 
Example #20
Source File: HttpClientUtils.java    From JobX with Apache License 2.0 5 votes vote down vote up
public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
        throws UnsupportedEncodingException {
    HttpPost httpPost = new HttpPost(url);

    for (Map.Entry<String, Object> param : headers.entrySet()) {
        httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
    }

    ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
    httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

    return getResult(httpPost);
}
 
Example #21
Source File: HttpClientUtils.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
public static String doPost(SqlToyContext sqltoyContext, final String url, String username, String password,
		String[] paramName, String[] paramValue) throws Exception {
	HttpPost httpPost = new HttpPost(url);
	// 设置connection是否自动关闭
	httpPost.setHeader("Connection", "close");
	httpPost.setConfig(requestConfig);
	CloseableHttpClient client = null;
	try {
		if (StringUtil.isNotBlank(username) && StringUtil.isNotBlank(password)) {
			// 凭据提供器
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(AuthScope.ANY,
					// 认证用户名和密码
					new UsernamePasswordCredentials(username, password));
			client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
		} else {
			client = HttpClients.createDefault();
		}
		if (paramValue != null && paramValue.length > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (int i = 0; i < paramValue.length; i++) {
				if (paramValue[i] != null) {
					nvps.add(new BasicNameValuePair(paramName[i], paramValue[i]));
				}
			}
			HttpEntity httpEntity = new UrlEncodedFormEntity(nvps, CHARSET);
			((UrlEncodedFormEntity) httpEntity).setContentType(CONTENT_TYPE);
			httpPost.setEntity(httpEntity);
		}
		HttpResponse response = client.execute(httpPost);
		// 返回结果
		HttpEntity reponseEntity = response.getEntity();
		if (reponseEntity != null) {
			return EntityUtils.toString(reponseEntity, CHARSET);
		}
	} catch (Exception e) {
		throw e;
	}
	return null;
}
 
Example #22
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
protected void attemptItemAction (final HttpClient client, final ServiceRef svc, final String itemSid, final ItemAction itemAction) throws IOException {
	final HttpPost post = new HttpPost(BASE_URL + API_ACTION);
	final List<NameValuePair> params = new ArrayList<NameValuePair>(4);
	addAuthParams(params);
	params.add(new BasicNameValuePair("service", svc.getRawType()));
	params.add(new BasicNameValuePair("uid", svc.getUid()));
	params.add(new BasicNameValuePair("postid", itemSid));
	params.add(new BasicNameValuePair("action", itemAction.getAction()));

	post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
	client.execute(post, new CheckStatusOnlyHandler());
}
 
Example #23
Source File: EmailUtil.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to send a HTTP post request.
 *
 * @param   url             destination url.
 * @param  urlParameters    list of parameters for post request (username , password etc)
 * @return                  response of the post request.
 */
private static HttpResponse sendPOSTMessage(String url, List<NameValuePair> urlParameters) throws Exception {
    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", USER_AGENT);
    post.addHeader("Referer", url);
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    return httpClient.execute(post);
}
 
Example #24
Source File: FileSearchParser.java    From clouddisk with MIT License 5 votes vote down vote up
@Override
public HttpPost initRequest(final FileSearchParameter parameter) {
	final HttpPost request = new HttpPost(getRequestUri());
	final List<NameValuePair> data = new ArrayList<>(5);
	data.add(new BasicNameValuePair(CONST.KEY_NAME, parameter.getKey()));
	data.add(new BasicNameValuePair(CONST.ISFPATH_NAME, "1"));
	data.add(new BasicNameValuePair(CONST.PAGE_NAME, String.valueOf(parameter.getPage())));
	data.add(new BasicNameValuePair(CONST.PAGE_SIZE_NAME, String.valueOf(parameter.getPage_size())));
	data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
	return request;
}
 
Example #25
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
protected HttpPost getPostMethodWithParamsInBody(URI uri, String message, ParameterValueList parameters, IPipeLineSession session) throws SenderException {
	HttpPost hmethod = new HttpPost(uri);

	if (!isMultipart() && StringUtils.isEmpty(getMultipartXmlSessionKey())) {
		List<NameValuePair> requestFormElements = new ArrayList<NameValuePair>();

		if (StringUtils.isNotEmpty(getInputMessageParam())) {
			requestFormElements.add(new BasicNameValuePair(getInputMessageParam(),message));
			log.debug(getLogPrefix()+"appended parameter ["+getInputMessageParam()+"] with value ["+message+"]");
		}
		if (parameters!=null) {
			for(int i=0; i<parameters.size(); i++) {
				ParameterValue pv = parameters.getParameterValue(i);
				String name = pv.getDefinition().getName();
				String value = pv.asStringValue("");

				// Skip parameters that are configured as ignored
				if (skipParameter(name))
					continue;

				requestFormElements.add(new BasicNameValuePair(name,value));
				if (log.isDebugEnabled()) log.debug(getLogPrefix()+"appended parameter ["+name+"] with value ["+value+"]");
			}
		}
		try {
			hmethod.setEntity(new UrlEncodedFormEntity(requestFormElements, getCharSet()));
		} catch (UnsupportedEncodingException e) {
			throw new SenderException(getLogPrefix()+"unsupported encoding for one or more post parameters");
		}
	}
	else {
		HttpEntity requestEntity = createMultiPartEntity(message, parameters, session);
		hmethod.setEntity(requestEntity);
	}

	return hmethod;
}
 
Example #26
Source File: HttpUtils.java    From lorne_core with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: HttpClientService.java    From jstorm with Apache License 2.0 5 votes vote down vote up
protected String excutePost(String url, List<NameValuePair> nvps) throws Exception {
	HttpClient httpClient = getHttpClient();
	HttpPost httpPost = new HttpPost(url);
	httpPost.setEntity(new UrlEncodedFormEntity(nvps));
	HttpResponse httpResponse = httpClient.execute(httpPost);
	String response = parseResponse(url, httpResponse);
	return response;
}
 
Example #28
Source File: HttpUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public static HttpResult postStream(CloseableHttpClient client, Map<String, String> headers, String url, String encode, Map<String, Object> params) {
	List<HttpEntity> entitys = new ArrayList<HttpEntity>();
	if(null != params && !params.isEmpty()){
		List<NameValuePair> pairs = packNameValuePair(params);
		try {
			HttpEntity entity = new UrlEncodedFormEntity(pairs, encode);
			entitys.add(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	return postStream(client, headers, url, encode, entitys);
}
 
Example #29
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public String requestHttpPost(String url_prex, String url, Map<String, String> params)
		throws HttpException, IOException {
	IdleConnectionMonitor();
	url = url_prex + url;
	HttpPost method = this.httpPostMethod(url);
	List<NameValuePair> valuePairs = this.convertMap2PostParams(params);
	UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
	method.setEntity(urlEncodedFormEntity);
	method.setConfig(requestConfig);
	HttpResponse response = client.execute(method);
	// System.out.println(method.getURI());
	HttpEntity entity = response.getEntity();

	if (entity == null) {
		return "";
	}
	InputStream is = null;
	String responseData = "";
	try {
		is = entity.getContent();
		responseData = IOUtils.toString(is, "UTF-8");
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return responseData;

}
 
Example #30
Source File: HeartbeatAdapter.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * Handle the packaging and sending of a hearbeat call to a remote directory
 *
 * @param fromPlace the key of the place location sending
 * @param toPlace the keyof the place location to receive
 * @return status of operation
 */
public EmissaryResponse outboundHeartbeat(final String fromPlace, final String toPlace) {

    final String directoryUrl = KeyManipulator.getServiceHostURL(toPlace);
    final HttpPost method = new HttpPost(directoryUrl + CONTEXT + "/Heartbeat.action");

    final String loc = KeyManipulator.getServiceLocation(toPlace);

    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(FROM_PLACE_NAME, fromPlace));
    nvps.add(new BasicNameValuePair(TO_PLACE_NAME, loc));
    method.setEntity(new UrlEncodedFormEntity(nvps, java.nio.charset.Charset.defaultCharset()));

    return send(method);
}