public static String doPostWithHeader(String url, List<Header> headerList, Map<String, Object> params, boolean isFormData) throws Exception {
logger.debug("Post Url:" + url + ",Params:" + params);
StringBuffer result = new StringBuffer();
HttpClient client = new HttpClient();
client.getParams().setIntParameter("http.connection.timeout", 10000);
if (url.startsWith("https")) {
Protocol myhttps = new Protocol("https", new HttpSSLProtocolSocketHandler(), 443);
Protocol.registerProtocol("https", myhttps);
}
PostMethod method = new PostMethod(url);
method.getParams().setParameter("http.protocol.content-charset", "UTF-8");
method.addRequestHeader(new Header("Content-Type", isFormData ? "application/x-www-form-urlencoded" : "application/json"));
Header str;
if (headerList != null && headerList.size() > 0) {
Iterator var7 = headerList.iterator();
while(var7.hasNext()) {
str = (Header)var7.next();
method.addRequestHeader(str);
}
}
if (isFormData) {
if (!ObjectUtils.isEmpty(params)) {
NameValuePair[] data = new NameValuePair[params.size()];
int i = 0;
Map.Entry entry;
for(Iterator i$ = params.entrySet().iterator(); i$.hasNext(); data[i++] = new NameValuePair((String)entry.getKey(), (String)entry.getValue())) {
entry = (Map.Entry)i$.next();
}
method.setRequestBody(data);
}
} else if (params != null) {
String requestJson = JSONObject.toJSONString(params);
method.setRequestBody(requestJson);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), StandardCharsets.UTF_8));
str = null;
String str;
while((str = reader.readLine()) != null) {
result.append(str);
}
}
} finally {
method.releaseConnection();
}
logger.debug("Post Return:" + result.toString());
return result.toString();
}
java post请求
最新推荐文章于 2024-07-27 10:18:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)