Java傳送Post請求
1,傳送正常post請求
public String executePost(String url, Map<String, String> params, Map<String, String> headers,
String charSet) {
CloseableHttpClient httpclient = getHttpClient();
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(new URIBuilder(url).build());
if (headers != null) {
post.setHeaders(assemblyHeader(headers));
}
// 設定HTTP POST請求引數必須用NameValuePair物件
List<NameValuePair> lst = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
lst.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 設定HTTP POST請求引數
UrlEncodedFormEntity posEntity = new UrlEncodedFormEntity(lst, charSet);
if (logger.isDebugEnabled()) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
posEntity.writeTo(os);
logger.debug("url:{},content:{}", url, os.toString());
}
post.setEntity(posEntity);
post.setConfig(requestConfig);
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, charSet);
} catch (Exception e) {
logger.error(e.getMessage() + " when url is:" + url, e);
return null;
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
2傳送json post請求
private String sendPostByJson(String url, Map<String, Object> params,
Map<String, String> headers) {
CloseableHttpClient httpclient = httpClient.getHttpClient();
HttpPost post = new HttpPost(url);
if (params != null && !params.isEmpty()) {
List<Header> tmpHeaders = new ArrayList<>();
tmpHeaders.add(
new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()));
if (headers != null) {
headers.keySet().stream().forEach(key -> {
Header header = new BasicHeader(key, headers.get(key));
tmpHeaders.add(header);
});
}
post.setHeaders(tmpHeaders.toArray(new Header[] {}));
String json = ObjectMapperUtils.toJSON(params);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(entity);
}
int timeout = (int) TimeUnit.MINUTES.toMillis(3);
RequestConfig timeOutRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
post.setConfig(timeOutRequestConfig);
return execAndHandleThrowable(() -> {
CloseableHttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
return EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
}, e -> logger.error(e.getMessage() + " when send json to server"));
}
3,send form data post請求
public String sendPostByFormData(String url, Map<String, Object> params,
Map<String, String> headers) {
CloseableHttpClient httpclient = httpClient.getHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
params.keySet().stream().forEach(key -> {
Object o = params.get(key);
if (o != null) {
if (o instanceof File) {
File file = (File) o;
builder.addBinaryBody(key, file, ContentType.MULTIPART_FORM_DATA,
StringUtils.defaultString(file.getName()));
} else {
StringBody stringBody = new StringBody(o.toString(),
ContentType.MULTIPART_FORM_DATA);
builder.addPart(key, stringBody);
}
}
});
}
List<Header> tmpHeaders = new ArrayList<>();
if (headers != null) {
headers.keySet().stream().forEach(key -> {
Header header = new BasicHeader(key, headers.get(key));
tmpHeaders.add(header);
});
}
post.setHeaders(tmpHeaders.toArray(new Header[] {}));
HttpEntity fileEntry = builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).build();
post.setEntity(fileEntry);
int timeout = (int) TimeUnit.MINUTES.toMillis(KConfDefault.TEN);
RequestConfig timeOutRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
post.setConfig(timeOutRequestConfig);
return execAndHandleThrowable(() -> {
CloseableHttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
return EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
}, e -> logger.error(e.getMessage() + " when send form data"));
}
4, 可以通過header判斷髮送哪個請求
public String sendPost(String url, Map<String, Object> params, Map<String, String> headers) {
if (StringUtils.isEmpty(url)) {
return null;
}
if (checkMapKeyValueEqual(headers, "Content-Type",
ContentType.APPLICATION_JSON.getMimeType())) {
return sendPostByJson(url, params, headers);
} else if (checkMapKeyValueEqual(headers, "Content-Type",
ContentType.MULTIPART_FORM_DATA.getMimeType())) {
return sendPostByFormData(url, params, headers);
}
return sendPostByCommon(url, params, headers);
}
private boolean checkMapKeyValueEqual(Map<String, String> map, String key, String value) {
if (map == null || map.isEmpty()) {
return false;
}
AtomicBoolean search = new AtomicBoolean(false);
map.keySet().stream().forEach(tmpKey -> {
if (!search.get() && StringUtils.equalsIgnoreCase(key, tmpKey)
&& StringUtils.equalsIgnoreCase(value, map.get(tmpKey))) {
search.set(true);
}
});
return search.get();
}
相關文章
- java傳送GET和post請求Java
- java傳送http的get、post請求JavaHTTP
- Postman傳送Post請求Postman
- java傳送post請求 ,請求資料放到body裡Java
- C# 傳送POST請求C#
- python傳送HTTP POST請求PythonHTTP
- post 封裝Map 傳送請求封裝
- PHP傳送POST和GET請求PHP
- 用Fiddler 傳送post請求
- 使用C#傳送POST請求C#
- linux用curl傳送post請求Linux
- 以Raw的方式傳送POST請求
- httprequest- post- get -傳送請求HTTP
- php 利用socket傳送GET,POST請求PHP
- 使用Postman傳送POST請求的指南Postman
- SpringMVC中如何傳送GET請求、POST請求、PUT請求、DELETE請求。SpringMVCdelete
- 【轉】怎麼用PHP傳送HTTP請求(POST請求、GET請求)?PHPHTTP
- java傳送http請求JavaHTTP
- postman(二):使用postman傳送get or post請求Postman
- curl 傳送 POST 請求的四種方式
- file_get_contents傳送post請求
- 【Postman】6 Postman 傳送post請求-Json格式PostmanJSON
- cURL實現傳送Get和Post請求(PHP)PHP
- oracle使用utl_http包傳送post請求OracleHTTP
- Java用HttpClient3傳送http/https協議get/post請求,傳送map,jsoJavaHTTPclient協議JS
- java post 請求Java
- jmeter之傳送json資料的post請求JMeterJSON
- Go語言開發傳送Get和Post請求Go
- 利用post請求傳送內容進行爬蟲爬蟲
- java apache commons HttpClient傳送get和post請求的學習整理JavaApacheHTTPclient
- scrapy-redis原始碼解讀之傳送POST請求Redis原始碼
- axios傳送post請求,request.getParamter接收不到iOS
- 關於用URL類傳送POST請求的問題?
- java傳送get請求帶引數Java
- 『動善時』JMeter基礎 — 14、使用JMeter傳送Post請求JMeter
- python+pytest介面自動化傳送post請求Python
- Golang:使用go-resty/resty傳送http請求get和postGolangRESTHTTP
- Java用HttpClient3傳送http/https協議get/post請求,傳送map,json,xml,txt資料JavaHTTPclient協議JSONXML