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
- Postman傳送Post請求Postman
- python傳送HTTP POST請求PythonHTTP
- linux用curl傳送post請求Linux
- SpringMVC中如何傳送GET請求、POST請求、PUT請求、DELETE請求。SpringMVCdelete
- 使用Postman傳送POST請求的指南Postman
- 以Raw的方式傳送POST請求
- file_get_contents傳送post請求
- httprequest- post- get -傳送請求HTTP
- 【Postman】6 Postman 傳送post請求-Json格式PostmanJSON
- curl 傳送 POST 請求的四種方式
- postman(二):使用postman傳送get or post請求Postman
- java傳送http請求JavaHTTP
- Java用HttpClient3傳送http/https協議get/post請求,傳送map,jsoJavaHTTPclient協議JS
- cURL實現傳送Get和Post請求(PHP)PHP
- jmeter之傳送json資料的post請求JMeterJSON
- java apache commons HttpClient傳送get和post請求的學習整理JavaApacheHTTPclient
- java post 請求Java
- python+pytest介面自動化傳送post請求Python
- axios傳送post請求,request.getParamter接收不到iOS
- 利用post請求傳送內容進行爬蟲爬蟲
- scrapy-redis原始碼解讀之傳送POST請求Redis原始碼
- Java用HttpClient3傳送http/https協議get/post請求,傳送map,json,xml,txt資料JavaHTTPclient協議JSONXML
- java傳送get請求帶引數Java
- Golang:使用go-resty/resty傳送http請求get和postGolangRESTHTTP
- 『動善時』JMeter基礎 — 14、使用JMeter傳送Post請求JMeter
- Vue中通過Axios向SpringBoot傳送get和post請求VueiOSSpring Boot
- Java 監聽POST請求Java
- Android 傳送HTTP GET POST 請求以及通過 MultipartEntityBuilder 上傳檔案(二)AndroidHTTPUI
- 『居善地』介面測試 — 5、使用Requests庫傳送POST請求
- nGrinder中快速編寫groovy指令碼04-傳送POST請求指令碼
- Python開發技巧:scrapy-redis爬蟲如何傳送POST請求PythonRedis爬蟲
- 傳送GET請求 示例
- 請問上傳的檔案如何傳送post
- 使用Feign傳送HTTP請求HTTP
- 如何傳送請求以及AJAX
- vue2.0 axios post請求傳參問題(ajax請求)VueiOS
- Java Http Get Post 請求工具類JavaHTTP