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

The following examples show how to use org.apache.http.client.entity.UrlEncodedFormEntity. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: extract   Source File: RESTSpewer.java    License: 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 2
Source Project: incubator-gobblin   Source File: CouchbaseWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source Project: web-sso   Source File: LogoutAppServiceImpl.java    License: 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 4
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 5
Source Project: roncoo-education   Source File: HttpUtil.java    License: 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 6
Source Project: pinpoint   Source File: HttpRemoteService.java    License: 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 7
Source Project: spring-cloud-dataflow   Source File: TaskControllerTests.java    License: 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 8
Source Project: knox   Source File: TempletonDemo.java    License: 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 9
Source Project: rdf4j   Source File: ProtocolTest.java    License: 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 10
Source Project: wisdom   Source File: MultipartBody.java    License: 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 11
Source Project: curly   Source File: ActionRunner.java    License: 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 12
Source Project: keycloak   Source File: RegistrationRecaptcha.java    License: 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 13
Source Project: geoportal-server-harvester   Source File: AgsClient.java    License: 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 14
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 15
Source Project: nano-framework   Source File: AbstractHttpClient.java    License: 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 16
Source Project: docs-apim   Source File: 103335311.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Authenticate to external APIStore
 *
 * @param httpContext  HTTPContext
 */
private boolean authenticateAPIM(APIStore store,HttpContext httpContext) throws APIManagementException {
    try {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        String storeEndpoint=store.getEndpoint();
        if(store.getEndpoint().contains("/store")){
        storeEndpoint=store.getEndpoint().split("store")[0]+"publisher"+APIConstants.APISTORE_LOGIN_URL;
        }
        else if(!generateEndpoint(store.getEndpoint())){
            storeEndpoint=storeEndpoint+ APIConstants.APISTORE_LOGIN_URL;
        }
        HttpPost httppost = new HttpPost(storeEndpoint);
        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(3);

        params.add(new BasicNameValuePair(APIConstants.API_ACTION, APIConstants.API_LOGIN_ACTION));
        params.add(new BasicNameValuePair(APIConstants.APISTORE_LOGIN_USERNAME, store.getUsername()));
        params.add(new BasicNameValuePair(APIConstants.APISTORE_LOGIN_PASSWORD, store.getPassword()));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpclient.execute(httppost, httpContext);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        boolean isError=Boolean.parseBoolean(responseString.split(",")[0].split(":")[1].split("}")[0].trim());


        if (isError) {
            String errorMsg=responseString.split(",")[1].split(":")[1].split("}")[0].trim();
            throw new APIManagementException(" Authentication with external APIStore - "+store.getDisplayName()+ "  failed due to "+errorMsg+".API publishing to APIStore- "+store.getDisplayName()+" failed.");

        } else{
            return true;
        }

    } catch (IOException e) {
        throw new APIManagementException("Error while accessing the external store : "+ store.getDisplayName() +" : "+e.getMessage(), e);

    }
}
 
Example 17
Source Project: rest-framework   Source File: RestExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the hashmap turns it in HttpEntity nameValuePair.
 * 
 * @param inputEntities
 * @return
 */
private HttpEntity getEntities(HashMap<String, String> inputEntities) {
	List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(inputEntities.size());
	Set<String> keys = inputEntities.keySet();
	for (String key : keys) {
		nameValuePairs.add(new BasicNameValuePair(key, inputEntities.get(key)));
	}
	try {
		return new UrlEncodedFormEntity(nameValuePairs);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 18
Source Project: triplea   Source File: MartiDiceRoller.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String postRequest(
    final int max, final int numDice, final String subjectMessage, final String gameId)
    throws IOException {
  final String normalizedGameId = gameId.isBlank() ? "TripleA" : gameId;
  String message = normalizedGameId + ":" + subjectMessage;
  if (message.length() > MESSAGE_MAX_LENGTH) {
    message = message.substring(0, MESSAGE_MAX_LENGTH - 1);
  }
  try (CloseableHttpClient httpClient =
      HttpClientBuilder.create().setRedirectStrategy(new AdvancedRedirectStrategy()).build()) {
    final HttpPost httpPost = new HttpPost(DICE_ROLLER_PATH);
    final List<NameValuePair> params =
        ImmutableList.of(
            new BasicNameValuePair("numdice", String.valueOf(numDice)),
            new BasicNameValuePair("numsides", String.valueOf(max)),
            new BasicNameValuePair("subject", message),
            new BasicNameValuePair("roller", getToAddress()),
            new BasicNameValuePair("gm", getCcAddress()));
    httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
    httpPost.addHeader("User-Agent", "triplea/" + ClientContext.engineVersion());
    final HttpHost hostConfig =
        new HttpHost(diceRollerUri.getHost(), diceRollerUri.getPort(), diceRollerUri.getScheme());
    HttpProxy.addProxy(httpPost);
    try (CloseableHttpResponse response = httpClient.execute(hostConfig, httpPost)) {
      return EntityUtils.toString(response.getEntity());
    }
  }
}
 
Example 19
Source Project: ehousechina   Source File: JenKinsBuildService.java    License: Apache License 2.0 5 votes vote down vote up
public void build(String jobName,Map<String,String> parameters) {
	String fmt="http://%s:%s/job/%s/buildWithParameters";
	CrumbEntity crumbEntity = getCrumb();
	HttpPost httpPost = new HttpPost(String.format(fmt, jenKinsHost,jenKinsPort,jobName));
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	for (String key : parameters.keySet()) {
		formparams.add(new BasicNameValuePair(key, parameters.get(key)));
    }
	UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	CloseableHttpResponse rsp = null;
	try {
		httpPost.setEntity(urlEntity);
		httpPost.addHeader(crumbEntity.getCrumbRequestField(),crumbEntity.getCrumb());
		rsp = httpClient.execute(httpPost, this.getHttpClientContext());
	} catch (Exception e) {
		log.error(null, e);
	}finally{
		HttpUtil.close(rsp);
		fmt=null;
		crumbEntity=null;
		httpPost=null;
		formparams.clear();
		parameters.clear();
		formparams=null;
		parameters=null;
	}
}
 
Example 20
Source Project: ticket   Source File: ApiRequestService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean submitOrderRequest(BuyTicketInfoModel buyTicketInfoModel,
        TicketModel ticketModel) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore
            .get(buyTicketInfoModel.getUsername());
    SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    HttpPost httpPost = new HttpPost(apiConfig.getSubmitOrderRequest());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("back_train_date", shortSdf.format(cal.getTime())));
    formparams.add(new BasicNameValuePair("purpose_codes", "ADULT"));
    formparams.add(new BasicNameValuePair("query_from_station_name",
            Station.getNameByCode(buyTicketInfoModel.getTo())));
    formparams.add(new BasicNameValuePair("query_to_station_name",
            Station.getNameByCode(buyTicketInfoModel.getFrom())));
    formparams.add(new BasicNameValuePair("secretStr", ticketModel.getSecret()));
    formparams.add(new BasicNameValuePair("train_date", buyTicketInfoModel.getDate()));
    formparams.add(new BasicNameValuePair("tour_flag", "dc"));
    formparams.add(new BasicNameValuePair("undefined", ""));

    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    String response = httpUtil.post(httpPost);
    Gson jsonResult = new Gson();
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if (null != rsmap.get("status") && rsmap.get("status").toString().equals("true")) {
        log.info("点击预定按钮成功");
        return true;

    } else if (null != rsmap.get("status") && rsmap.get("status").toString().equals("false")) {
        String errMsg = rsmap.get("messages") + "";
        log.error(errMsg);
    }
    return false;
}
 
Example 21
/**
 * Send post request to the {@link #getEndpointUrl()} with suffix as a url
 * parameter.
 * 
 * @param url
 *            suffix to the {@link #getEndpointUrl()}.
 * @param parameters
 *            map of parameters that will be attached to the request
 * @return response of the request
 * @throws HttpResponseException
 * @throws IOException
 */
protected String sendPostRequest(final String url, final Map<String, String> parameters)
		throws HttpResponseException, IOException {
	final HttpPost postRequest = new HttpPost(getEndpointUrl() + url);
	final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(getTimeout()).build();

	postRequest.setConfig(requestConfig);
	postRequest.addHeader(getxCsrfToken(), getCsrfToken());
	postRequest.setEntity(new UrlEncodedFormEntity(createParametersList(parameters)));

	final HttpResponse response = getHttpClient().execute(postRequest, getContext());
	final String responseBody = new BasicResponseHandler().handleResponse(response);

	return responseBody;
}
 
Example 22
Source Project: newblog   Source File: HttpHelper.java    License: Apache License 2.0 5 votes vote down vote up
public String doPostLongWait(String url, List<NameValuePair> pairs, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    log.info(" post url=" + url);
    try {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300000)
                .setConnectTimeout(30000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, charset);
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    } catch (Exception e) {
        log.error("to request addr=" + url + ", " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}
 
Example 23
Source Project: NNAnalytics   Source File: TestLdapAuth.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalAuthentication() throws IOException {
  // Test authentication required.
  HttpGet get = new HttpGet("http://localhost:4567/info");
  HttpResponse res = client.execute(hostPort, get);
  System.out.println(IOUtils.toString(res.getEntity().getContent()));
  assertThat(res.getStatusLine().getStatusCode(), is(401));

  // Do local auth.
  HttpPost post = new HttpPost("http://localhost:4567/login");
  List<NameValuePair> postParams = new ArrayList<>();
  postParams.add(new BasicNameValuePair("username", "hdfs"));
  postParams.add(new BasicNameValuePair("password", "hdfs"));
  post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
  HttpResponse res2 = client.execute(hostPort, post);
  System.out.println(IOUtils.toString(res2.getEntity().getContent()));
  assertThat(res2.getStatusLine().getStatusCode(), is(200));

  // Use JWT to auth again.
  Header tokenHeader = res2.getFirstHeader("Set-Cookie");
  HttpGet get2 = new HttpGet("http://localhost:4567/threads");
  get2.addHeader("Cookie", tokenHeader.getValue());
  HttpResponse res3 = client.execute(hostPort, get2);
  IOUtils.readLines(res3.getEntity().getContent()).clear();
  assertThat(res3.getStatusLine().getStatusCode(), is(200));

  // Check credentials exist.
  HttpGet get3 = new HttpGet("http://localhost:4567/credentials");
  get3.addHeader("Cookie", tokenHeader.getValue());
  HttpResponse res4 = client.execute(hostPort, get3);
  IOUtils.readLines(res4.getEntity().getContent()).clear();
  assertThat(res4.getStatusLine().getStatusCode(), is(200));
}
 
Example 24
Source Project: slack-api   Source File: RestUtils.java    License: MIT License 5 votes vote down vote up
public static HttpEntity createUrlEncodedFormEntity(Map<String, String> parameters) {
	List<NameValuePair> nvps = new ArrayList<NameValuePair>(parameters.size());
	for (Entry<String, String> entry : parameters.entrySet()) {
		if (entry.getValue() != null) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
	}
	return new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8"));
}
 
Example 25
Source Project: keycloak   Source File: MutualTLSClientTest.java    License: Apache License 2.0 5 votes vote down vote up
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 26
private String doPostLogin(String username, String password) throws Exception {
	
	CloseableHttpClient httpclient = getHTTPClient(username, password);

	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("username", username));
	formparams.add(new BasicNameValuePair("password", password));
	
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/auth/login");
	httppost.setEntity(entity);	

	CloseableHttpResponse response = httpclient.execute(httppost);
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
			return respoBody;
		}
	} finally {
		response.close();
	}

	return null;
}
 
Example 27
Source Project: knox   Source File: PostRequest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequestBase createRequest() {
  HttpRequestBase request = super.createRequest();
  List<NameValuePair> formData = new ArrayList<>();
  formData.add(new BasicNameValuePair(FORM_PARAM_VALUE, pwd));
  ((HttpPost) request).setEntity(new UrlEncodedFormEntity(formData, StandardCharsets.UTF_8));
  return request;
}
 
Example 28
Source Project: emissary   Source File: HeartbeatAdapter.java    License: 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);
}
 
Example 29
Source Project: zheshiyigeniubidexiangmu   Source File: HttpUtilManager.java    License: 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 Project: anyline   Source File: HttpUtil.java    License: 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 31
Source Project: jstorm   Source File: HttpClientService.java    License: 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 32
Source Project: lorne_core   Source File: HttpUtils.java    License: 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 33
Source Project: iaf   Source File: HttpSender.java    License: 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 34
Source Project: NNAnalytics   Source File: TestNNAnalyticsBase.java    License: 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 35
Source Project: product-es   Source File: EmailUtil.java    License: 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 36
Source Project: neembuu-uploader   Source File: FilePup.java    License: 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 37
Source Project: charging_pile_cloud   Source File: HttpClientUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 封装HTTP PUT方法
 *
 * @param
 * @param
 * @return
 */
public static String put(String url, Map<String, String> paramMap)
        throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(url);
    List<NameValuePair> formparams = setHttpParams(paramMap);
    UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
    httpPut.setEntity(param);
    HttpResponse response = httpClient.execute(httpPut);
    String httpEntityContent = getHttpEntityContent(response);
    httpPut.abort();
    return httpEntityContent;
}
 
Example 38
Source Project: clouddisk   Source File: FileSearchParser.java    License: 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 39
Source Project: DataSphereStudio   Source File: AzkabanProjectService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * delete=boolean
 * project=projectName
 *
 * @param project
 * @param session
 */
@Override
public void deleteProject(Project project, Session session) throws AppJointErrorException {
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("delete", "true"));
    params.add(new BasicNameValuePair("project", project.getName()));
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(session.getCookies()[0]);
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = null;
    try {
        String finalUrl = projectUrl + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params));
        HttpGet httpGet = new HttpGet(finalUrl);
        httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        response = httpClient.execute(httpGet, context);
        Header[] allHeaders = context.getRequest().getAllHeaders();
        Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getName())).findFirst();
        header.ifPresent(DSSExceptionUtils.handling(this::parseCookie));
    } catch (Exception e) {
        logger.error("delete scheduler project failed,reason:",e);
        throw new AppJointErrorException(90010, e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example 40
Source Project: bobcat   Source File: CreatePage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Step("Create test page {data.contentPath}")
public void execute(SlingPageData data) throws AemPageManipulationException {
  HttpPost request = new HttpPost(authorIP + data.getContentPath());
  request.setEntity(new UrlEncodedFormEntity(data.getContent(), Consts.UTF_8));
  try {
    httpClient.execute(request);
  } catch (IOException e) {
    throw new AemPageManipulationException(e);
  }
}