下面列出了org.apache.http.client.entity.UrlEncodedFormEntity# setContentType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* 构建FormEntity
*
* @param formParam
* @return
* @throws UnsupportedEncodingException
*/
private static UrlEncodedFormEntity buildFormEntity(Map<String, String> formParam)
throws UnsupportedEncodingException {
if (formParam != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : formParam.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, formParam.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Constants.ENCODING);
formEntity.setContentType(ContentType.CONTENT_TYPE_FORM);
return formEntity;
}
return null;
}
/**
* Generate a FusionTables POST request
*/
// To be deprecated, based on the old API
private HttpUriRequest genFusiontablesQuery(String query) throws IOException {
HttpPost request = new HttpPost(FUSION_QUERY_URL);
ArrayList<BasicNameValuePair> pair = new ArrayList<BasicNameValuePair>(1);
pair.add(new BasicNameValuePair("sql", query));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair, "UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
request.setEntity(entity);
return request;
}
/**
* Authenticates the given username/password with the given eauth system
* against the salt-api endpoint
*
* @param capability
* The {@link SaltApiCapability} that describes the supported features of the saltEndpoint
* @param user
* The user to auth with
* @param password
* The password for the given user
* @return X-Auth-Token for use in subsequent requests
*/
protected String authenticate(final SaltApiCapability capability, HttpClient client, String user, String password) throws IOException, HttpException,
InterruptedException {
List<NameValuePair> params = Lists.newArrayListWithCapacity(3);
params.add(new BasicNameValuePair(SALT_API_USERNAME_PARAM_NAME, user));
params.add(new BasicNameValuePair(SALT_API_PASSWORD_PARAM_NAME, password));
params.add(new BasicNameValuePair(SALT_API_EAUTH_PARAM_NAME, eAuth));
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, CHAR_SET_ENCODING);
postEntity.setContentEncoding(CHAR_SET_ENCODING);
postEntity.setContentType(REQUEST_CONTENT_TYPE);
HttpPost post = httpFactory.createHttpPost(saltEndpoint + LOGIN_RESOURCE);
post.setEntity(postEntity);
logWrapper.info("Authenticating with salt-api endpoint: [%s]", post.getURI());
HttpResponse response = retryExecutor.execute(logWrapper, client, post, numRetries, new Predicate<Integer>() {
@Override
public boolean apply(Integer input) {
return input != capability.getLoginFailureResponseCode();
}
});
try {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == capability.getLoginSuccessResponseCode()) {
return response.getHeaders(SALT_AUTH_TOKEN_HEADER)[0].getValue();
} else if (responseCode == capability.getLoginFailureResponseCode()) {
return null;
} else {
throw new HttpException(String.format("Unexpected failure interacting with salt-api %s", response
.getStatusLine().toString()));
}
} finally {
closeResource(response.getEntity());
post.releaseConnection();
}
}
public static String downloadUrl(URI url, String cookies, String postData, Map<String, String> requestProperties, Charset charset) throws IOException {
HttpPost httpPost = new HttpPost(url);
HttpClientContext context = HttpClientContext.create();
RequestConfig.Builder builder = RequestConfig.custom();
builder.setConnectTimeout(2000).setConnectionRequestTimeout(2000).setSocketTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(true);
httpPost.setConfig(builder.build());
if (StringUtils.isNotBlank(cookies)) {
httpPost.setHeader("Cookie", cookies);
}
httpPost.setHeader("Accept", "*/*");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
if (requestProperties != null) {
for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
if (postData.startsWith("{")) {
httpPost.setEntity(new StringEntity(postData, ContentType.APPLICATION_JSON));
} else {
List<NameValuePair> nameValuePairs = new ArrayList<>();
String[] formItems = postData.split("&");
for (String formItem : formItems) {
String[] itemData = formItem.split("=");
nameValuePairs.add(new BasicNameValuePair(itemData[0], itemData.length > 1 ? itemData[1] : StringUtils.EMPTY));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, charset);
urlEncodedFormEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
httpPost.setEntity(urlEncodedFormEntity);
}
try (CloseableHttpResponse httpResponse = client.execute(httpPost, context)) {
HttpEntity responseEntity = httpResponse.getEntity();
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new IOException(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase() + "\n Headers:" + Arrays.toString(httpResponse.getAllHeaders()) + "\n" + EntityUtils.toString(responseEntity));
}
return EntityUtils.toString(responseEntity, charset);
} catch (IllegalStateException e) {
initClient();
throw e;
}
}
/**
* Submits the job to salt-api using the class function and args.
*
* @return the jid of the submitted job
* @throws HttpException
* if there was a communication failure with salt-api
* @throws InterruptedException
*/
protected String submitJob(SaltApiCapability capability, HttpClient client, String authToken, String minionId, Set<String> secureData) throws HttpException, IOException,
SaltApiException, SaltTargettingMismatchException, InterruptedException {
List<NameValuePair> params = Lists.newArrayList();
List<String> args = ArgumentParser.DEFAULT_ARGUMENT_SPLITTER.parse(function);
params.add(new BasicNameValuePair(SALT_API_FUNCTION_PARAM_NAME, args.get(0)));
params.add(new BasicNameValuePair(SALT_API_TARGET_PARAM_NAME, minionId));
List<NameValuePair> printableParams = Lists.newArrayList();
printableParams.addAll(params);
for (int i = 1; i < args.size(); i++) {
String value = args.get(i);
params.add(new BasicNameValuePair(SALT_API_ARGUMENTS_PARAM_NAME, value));
for (String s : secureData) {
value = StringUtils.replace(value, s, SECURE_OPTION_VALUE);
}
printableParams.add(new BasicNameValuePair(SALT_API_ARGUMENTS_PARAM_NAME, value));
}
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, CHAR_SET_ENCODING);
postEntity.setContentEncoding(CHAR_SET_ENCODING);
postEntity.setContentType(REQUEST_CONTENT_TYPE);
HttpPost post = httpFactory.createHttpPost(saltEndpoint + MINION_RESOURCE);
post.setHeader(SALT_AUTH_TOKEN_HEADER, authToken);
post.setHeader(REQUEST_ACCEPT_HEADER_NAME, JSON_RESPONSE_ACCEPT_TYPE);
post.setEntity(postEntity);
logWrapper.debug("Submitting job with arguments [%s]", printableParams);
logWrapper.info("Submitting job with salt-api endpoint: [%s]", post.getURI());
HttpResponse response = retryExecutor.execute(logWrapper, client, post, numRetries, Predicates.<Integer>alwaysFalse());
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
try {
String entityResponse = extractBodyFromEntity(entity);
if (statusCode != HttpStatus.SC_ACCEPTED) {
throw new HttpException(String.format("Expected response code %d, received %d. %s",
HttpStatus.SC_ACCEPTED, statusCode, entityResponse));
} else {
logWrapper.debug("Received response for job submission = %s", response);
SaltInteractionHandler interactionHandler = capability.getSaltInteractionHandler();
SaltApiResponseOutput saltOutput = interactionHandler.extractOutputForJobSubmissionResponse(entityResponse);
if (saltOutput.getMinions().size() != 1) {
throw new SaltTargettingMismatchException(String.format(
"Expected minion delegation count of 1, was %d. Full minion string: (%s)", saltOutput
.getMinions().size(), saltOutput.getMinions()));
} else if (!saltOutput.getMinions().contains(minionId)) {
throw new SaltTargettingMismatchException(String.format(
"Minion dispatch mis-match. Expected:%s, was:%s", minionId, saltOutput.getMinions()
.toString()));
}
return saltOutput.getJid();
}
} finally {
closeResource(entity);
post.releaseConnection();
}
}