下面列出了org.apache.http.client.methods.HttpTrace#org.apache.http.client.methods.HttpPost 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void pullAndInstall(final String remote, final String name,
final JsonArray properties)
throws IOException, UnexpectedResponseException {
final HttpPost pull =
new HttpPost(
new UncheckedUriBuilder(this.baseUri.toString().concat("/pull"))
.addParameter("remote", remote)
.addParameter("name", name)
.build()
);
try {
pull.setEntity(
new StringEntity(properties.toString())
);
this.client.execute(
pull,
new MatchStatus(
pull.getURI(),
HttpStatus.SC_NO_CONTENT
)
);
} finally {
pull.releaseConnection();
}
}
/**
* post访问
* @param url 地址
* @param body 访问数据
* @param contentType 访问的格式
* @return 访问返回值
*/
@Suspendable
public String doPost(String url, final String body, ContentType contentType){
HttpPost post = new HttpPost(url);
String str = "";
try {
StringEntity strEn = new StringEntity(body, contentType);
post.setEntity(strEn);
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
str = convertStreamToString(instreams);
logger.info("get http post response:{}", str);
}
}catch (Exception e){
logger.error("post exception:", e);
}finally {
post.abort();
}
return str;
}
@Test
public void greetClientCert() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(createTrustedClientCertSocketFactory(WILDFLY_HOME)).build()) {
HttpPost request = new HttpPost(CXF_ENDPOINT_URI);
request.setHeader("Content-Type", "text/xml");
request.setHeader("soapaction", "\"urn:greet\"");
request.setEntity(
new StringEntity(String.format(WS_MESSAGE_TEMPLATE, "Hi", "Joe"), StandardCharsets.UTF_8));
try (CloseableHttpResponse response = httpclient.execute(request)) {
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
Assert.assertTrue(body.contains("Hi Joe"));
}
}
}
public byte[] doPost(String sessionId) {
// FileEntity fe = new FileEntity();
// StringEntity se = new StringEntity("","");
try {
FileBody fileBody = new FileBody(new File(""));
StringBody stringBody = new StringBody("");
HttpPost httpPost = new HttpPost("");
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.addPart("name", fileBody);
meb.addPart("Sname",stringBody);
HttpEntity httpEntity = meb.build();
httpPost.setEntity(httpEntity);
}catch (Exception e){
}
// NameValuePair nameValuePair = new FileNa("","");
// eb.setParameters()
// HttpEntity httpEntity = eb.build();
// CloseableHttpPost httpPost = null;
// httpPost.setEntity(httpEntity);
// StringBody userName = new StringBody("Scott", ContentType.create(
// "text/plain", Consts.UTF_8));
return null;
}
/**
* @param url
* @param params
* @param header
* @param connectTimeout
* @param socketTimeout
* @return
* @throws IOException
*/
public String doPostForm(@NotNull String url, Map<String, String> params, Map<String, String> header, int connectTimeout, int socketTimeout) throws IOException {
Objects.requireNonNull(url, "http url cannot be bull");
/**
* 默认的httpclient
*/
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
handlerHeader(header, httpPost);
handlerRequestConfig(connectTimeout, socketTimeout, httpPost);
handlerParam(params, httpPost);
try {
return httpClient.execute(httpPost, new StringResponseHandler());
} finally {
httpClient.close();
}
}
public String record(TransactionContext transactionContext, CapitalTradeOrderDto tradeOrderDto) {
logger.info("CapitalTradeOrderService record method called.");
logger.info("Transaction ID:" + transactionContext.getXid().toString());
logger.info("Transaction status:" + transactionContext.getStatus());
try {
CapitalTradeOrderRecordRequest request = new CapitalTradeOrderRecordRequest();
request.setTransactionContext(transactionContext);
request.setCapitalTradeOrderDto(tradeOrderDto);
HttpPost post = new HttpPost("http://127.0.0.1:7001/record");
post.addHeader("Content-Type", "application/json");
StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(request));
post.setEntity(stringEntity);
CloseableHttpResponse response = closeableHttpClient.execute(post);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Capital trade order record request failed.");
}
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String uploadFile(String url, String path) throws IOException {
HttpPost post = new HttpPost(url);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(path)); //image should be a String
builder.addPart("file", fileBody);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
return readResponse(response);
} finally {
post.releaseConnection();
}
}
/**
* Overridden to obtain the Credentials from the CredentialsSource and pass
* them via HTTP BASIC Authorization.
*/
protected void setRequestBody(final HttpInvokerClientConfiguration config,
final HttpPost httpPost, final ByteArrayOutputStream baos) throws IOException {
final UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) this.credentialsSource.getCredentials(this.serviceConfiguration.getEndpointUrl().toExternalForm());
final String base64 = credentials.getUsername() + ":"
+ credentials.getPassword();
httpPost.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger
.debug("HttpInvocation now presenting via BASIC authentication CredentialsSource-derived: "
+ credentials.getUsername());
}
super.setRequestBody(config, httpPost, baos);
}
@Test
public void testMultipartCharacterEncoding() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String message = "abcčšž";
String charset = "UTF-8";
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext");
MultipartEntity multipart = new MultipartEntity();
multipart.addPart("charset", new StringBody(charset, Charset.forName(charset)));
multipart.addPart("message", new StringBody(message, Charset.forName(charset)));
post.setEntity(multipart);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
String response = HttpClientUtils.readResponse(result);
Assert.assertEquals(message, response);
} finally {
client.getConnectionManager().shutdown();
}
}
/**
* Use this method to publish using POST.
* @param payload - use the buildPayload method to retrieve NameValuePair to use as payload here.
* @param userAgent - set the userAgent - this can be overridden if userAgentOverride (ua) is set in payload
* @param useSSL - to publish using HTTPS, set this value to true.
* @return
*/
public static boolean publishPOST(List<NameValuePair> payload, String userAgent, boolean useSSL) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getURI(useSSL));
post.setHeader(GoogleAnalyticsConstants.HTTP_HEADER_USER_AGENT, userAgent);
try {
post.setEntity(new UrlEncodedFormEntity(payload));
HttpResponse response = client.execute(post);
if((response.getStatusLine().getStatusCode() == 200)
&& (response.getFirstHeader(GoogleAnalyticsConstants.HTTP_HEADER_CONTENT_TYPE).getValue()
.equals(GoogleAnalyticsConstants.RESPONSE_CONTENT_TYPE))) {
return true;
}
return false;
} catch (IOException e) {
return false;
}
}
/**
* 采用Post方式发送请求,获取响应数据
*
* @param url url地址
* @param param 参数值键值对的字符串
* @return
*/
public static String httpPost(String url, String param) {
CloseableHttpClient client = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
EntityBuilder builder = EntityBuilder.create();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setText(param);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
logger.info("状态:"+statusCode+"数据:"+data);
return data;
} catch(Exception e){
throw new RuntimeException(e.getMessage());
} finally {
try{
client.close();
}catch(Exception ex){ }
}
}
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String base) throws Exception {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
String value = params.get(key);
formparams.add(new BasicNameValuePair(key, value));
}
HttpPost request = new HttpPost(base);
RequestConfig localConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD)
.build();
request.setConfig(localConfig);
request.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
request.setHeader("Content-Type", "application/x-www-form-urlencoded"); //内容为post
return httpClient.execute(request);
}
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);
}
/**
*
* @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 "";
}
public String postDataToServer(List<NameValuePair> nvs, String url, String cookie) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
httpost.setHeader("Cookie", cookie);
StringBuilder sb = new StringBuilder();
// 设置表单提交编码为UTF-8
try {
httpost.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
InputStreamReader isr = new InputStreamReader(entity.getContent());
BufferedReader bufReader = new BufferedReader(isr);
String lineText = null;
while ((lineText = bufReader.readLine()) != null) {
sb.append(lineText);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return sb.toString();
}
/**
* Method by StupPlayer (https://github.com/StupPlayer)
* @param data
* @return
*/
public static String hastePost(String data) {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://hastebin.com/documents");
try {
post.setEntity(new StringEntity(data));
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
return "https://hastebin.com/" + new JsonParser().parse(result).getAsJsonObject().get("key").getAsString();
} catch (IOException e) {
e.printStackTrace();
}
return "Could not post!";
}
/**
* httpClient post 获取资源
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, Object> params) {
log.info(url);
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
Object object = params.get(key);
nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e);
}
return null;
}
private void openNetworkSession(String tempKey) {
Log.d(TAG, "Opening network session: " + tempKey);
if (!connected()) {
Log.d(TAG, "openNetworkSession()..connected = false");
openLocalSession(tempKey);
} else {
try {
Log.d(TAG, "openNetworkSession()..connected = true");
String[] credentials = tempSessions.get(tempKey);
HttpPost post = MDSInterface2.createSessionRequest(this,
credentials[0], credentials[1]);
Log.i(TAG, "openNetworkSession(...) " + post.getURI());
new HttpTask<String>(new AuthListener(tempKey)).execute(post);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
}
/**
* HTTP POST 字节数组
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param bodys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPost post = new HttpPost(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
if (bodys != null) {
post.setEntity(new ByteArrayEntity(bodys));
}
return convert(httpClient.execute(post));
}
public Session process() throws IOException {
HttpRequest request = this.getRequest();
Objects.requireNonNull(this.request);
HttpClient httpClient = this.getHttpClient();
HttpClientContext context = this.getContext();
if (request instanceof HttpGet) {
this.getContext().setCookieStore(cookies);
HttpGet get = (HttpGet) request;
this.httpResponse = httpClient.execute(get, context);
this.httpCode = httpResponse.getStatusLine().getStatusCode();
this.repUtils = new ResponseUtils(this.httpResponse);
} else if (this.request instanceof HttpPost) {
context.setCookieStore(cookies);
HttpPost post = (HttpPost) request;
post.setEntity(this.getProviderService().builder());
this.httpResponse = this.httpClient.execute(post, this.context);
this.httpCode = httpResponse.getStatusLine().getStatusCode();
this.repUtils = new ResponseUtils(this.httpResponse);
}
return this;
}
private <T> T requestResponse(String url, Object request, Class<T> responseClass) {
HttpPost post = new HttpPost(url);
try {
post.setEntity(new StringEntity(gson.toJson(request), ContentType.APPLICATION_JSON));
HttpResponse response = httpClient.execute(httpHost, post);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
throw new RuntimeIOException("Unexpected response code: " + status);
}
return gson.fromJson(EntityUtils.toString(response.getEntity()), responseClass);
} catch (IOException e) {
throw new RuntimeIOException("HTTP error: " + e, e);
}
}
/**
* Perform a POST request of XML (instead of using json mapper) and return a string rendering of
* the response entity.
*
* @param path
* path to request, can be relative or absolute
* @param XML
* data data to post
* @return A string containing the xml response (if present)
* @throws IOException
* , HttpResponseException
*/
public String post_xml(String path, String xml_data) throws IOException, HttpResponseException {
HttpPost request = new HttpPost(api(path));
if (xml_data != null) {
request.setEntity(new StringEntity(xml_data, ContentType.APPLICATION_XML));
}
HttpResponse response = client.execute(request, localContext);
int status = response.getStatusLine().getStatusCode();
if (status < 200 || status >= 300) {
throw new HttpResponseException(status, response.getStatusLine().getReasonPhrase());
}
try {
InputStream content = response.getEntity().getContent();
Scanner s = new Scanner(content, CHARSET_UTF_8);
StringBuffer sb = new StringBuffer();
while (s.hasNext()) {
sb.append(s.next());
}
return sb.toString();
} finally {
EntityUtils.consume(response.getEntity());
}
}
public static String sendJSONPost(String url, String jsonData, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEntity postEntity = new StringEntity(jsonData, CHARSET_NAME);
postEntity.setContentType("application/json");
httpPost.setEntity(postEntity);
httpPost.setHeader("Content-Type", "application/json");
HttpClient client = HttpClients.createDefault();
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
try {
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
logger.error("http request error ", e);
} finally {
httpPost.abort();
}
return result;
}
public static String doPost(String url, String paramStr, Map<String, String> headers) {
try {
HttpPost httppost = new HttpPost(url);
StringEntity str = new StringEntity(paramStr, ContentType.APPLICATION_JSON);
httppost.setEntity(str);
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
httppost.setHeader(header.getKey(), header.getValue());
}
}
return httpclient.execute(httppost, getResponseHandler());
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
/**
* 发送xml的post请求 指定contentType 和Charset
*
* @param url
* @param xml
* @param headers
* @return
*/
@Nullable
public static String postXML(String url, String xml, ContentType contentType,final Charset charset, Header... headers) {
CloseableHttpClient client = getHttpclient();
HttpPost httpPost = new HttpPost(url);
long start = System.currentTimeMillis();
try {
HttpEntity httpEntity = new StringEntity(xml,contentType);
if (headers != null && headers.length > 0) {
for (Header header : headers) {
httpPost.addHeader(header);
}
}
httpPost.setEntity(httpEntity);
CloseableHttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity, charset);
}
} catch (Exception e) {
logger.error("push xml fail,url:{}", url, e);
} finally {
long cost = System.currentTimeMillis() - start;
logger.info("httpUtil_postXml {}", cost);
httpPost.releaseConnection();
}
return null;
}
BasicResponse postJson(SwarmConfig config, String path, String body)
throws IOException, UnauthorizedAccessException {
final String url = toUrl(config, path, null);
final HttpPost request = new HttpPost(url);
final HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
request.setEntity(entity);
return request(config, request);
}
@Test public void createDeprecatedPostRequest() throws Exception {
TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);
HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
assertTrue(httpRequest instanceof HttpPost);
}
@Override
public HttpPost initRequest(final FileExistParameter parameter) {
final HttpPost request = new HttpPost(getRequestUri());
final List<NameValuePair> data = new ArrayList<>(0);
data.add(new BasicNameValuePair(CONST.DIR_NAME, parameter.getDir()));
data.addAll(parameter.getFnames().stream().map(fame -> new BasicNameValuePair(CONST.FNAME_NAME, fame)).collect(Collectors.toList()));
data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
return request;
}
/**
* Constructor.
*
* @param input the column metadata to get the actions for (in json).
*/
private SuggestColumnActions(InputStream input) {
super(GenericCommand.TRANSFORM_GROUP);
execute(() -> {
HttpPost post = new HttpPost(transformationServiceUrl + "/suggest/column");
post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
post.setEntity(new InputStreamEntity(input));
return post;
});
onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_RETRIEVE_SUGGESTED_ACTIONS, e));
on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(asNull());
on(HttpStatus.OK).then(pipeStream());
}
/**
* Method to claim task by a user
*
* @param taskID used to identify the task to be claimed
* @return String Array containing status
* @throws IOException
*/
public String claimTaskByTaskId(String taskID) throws IOException {
String url = serviceURL + "runtime/tasks/" + taskID;
DefaultHttpClient httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity params = new StringEntity("{\"action\" : \"claim\"," +
"\"assignee\" :\"" + USER_CLAIM + "\"}",
ContentType.APPLICATION_JSON);
httpPost.setEntity(params);
HttpResponse response = httpClient.execute(httpPost);
return response.getStatusLine().toString();
}