类org.apache.http.client.entity.UrlEncodedFormEntity源码实例Demo

下面列出了怎么用org.apache.http.client.entity.UrlEncodedFormEntity的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: extract   文件: RESTSpewer.java

@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);
}
 

/**
 * 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;
  }
}
 
源代码3 项目: web-sso   文件: LogoutAppServiceImpl.java

/**
 * 请求某个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();
	}
}
 
源代码4 项目: sana.mobile   文件: MDSInterface2.java

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);

}
 
源代码5 项目: roncoo-education   文件: HttpUtil.java

/**
 * 
 * @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 "";
}
 
源代码6 项目: pinpoint   文件: HttpRemoteService.java

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;
}
 

@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"));
}
 
源代码8 项目: knox   文件: TempletonDemo.java

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() ) );
}
 
源代码9 项目: rdf4j   文件: ProtocolTest.java

/**
 * 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);
}
 
源代码10 项目: wisdom   文件: MultipartBody.java

/**
 * 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);
        }
    }
}
 
源代码11 项目: curly   文件: ActionRunner.java

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));
    }
}
 
源代码12 项目: keycloak   文件: RegistrationRecaptcha.java

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;
}
 

/**
 * 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);
  }
}
 
源代码14 项目: PneumaticCraft   文件: PastebinHandler.java

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;
}
 
源代码15 项目: nano-framework   文件: AbstractHttpClient.java

/**
 * 根据请求信息创建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);
    }
}
 
源代码16 项目: docs-apim   文件: 103335311.java

/**
 * 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);

    }
}
 
源代码17 项目: rest-framework   文件: RestExecutor.java

/**
 * 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;
}
 
源代码18 项目: triplea   文件: MartiDiceRoller.java

@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());
    }
  }
}
 
源代码19 项目: ehousechina   文件: JenKinsBuildService.java

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;
	}
}
 
源代码20 项目: ticket   文件: ApiRequestService.java

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;
}
 

/**
 * 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;
}
 
源代码22 项目: newblog   文件: HttpHelper.java

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;
}
 
源代码23 项目: NNAnalytics   文件: TestLdapAuth.java

@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));
}
 
源代码24 项目: slack-api   文件: RestUtils.java

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"));
}
 
源代码25 项目: keycloak   文件: MutualTLSClientTest.java

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));
}
 

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;
}
 
源代码27 项目: knox   文件: PostRequest.java

@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;
}
 
源代码28 项目: emissary   文件: HeartbeatAdapter.java

/**
 * 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);
}
 

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;

}
 
源代码30 项目: anyline   文件: HttpUtil.java

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);
}
 
 类所在包
 同包方法