您的位置:首页 > 编程语言 > Java开发

用java代码模拟post请求

2014-01-03 15:54 375 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: