private String httpClientOfPosts(Map<String, String> parameters) {
String responseBody = null;
parameters = sortMap(parameters);
HttpClient httpClient = new HttpClient();
String host= "http://192.168.xx.xx:8080/app/tms.do";
PostMethod postMethod = new PostMethod(host);
postMethod.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");
NameValuePair[] data = new NameValuePair[parameters.size()];
int i = 0;
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
data[i] = new NameValuePair(parameter.getKey(), parameter
.getValue());
i++;
sb.append(parameter.getKey()+"="+parameter.getValue()+"&");
}
postMethod.setRequestBody(data);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
try {
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
responseBody = null;
}
responseBody = postMethod.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return responseBody;
}用java代码模拟post请求
最新推荐文章于 2023-09-16 13:16:52 发布
本文介绍了一种使用Java实现的HTTP客户端发送POST请求的方法。通过构造HttpClient实例,并设置请求头和参数,实现了向指定URL发送POST请求并获取响应的功能。

582

被折叠的 条评论
为什么被折叠?



