[color=green]urlString :接口请求地址
params:参数
encode:编码[/color]
params:参数
encode:编码[/color]
public static String post(String urlString, Map<String, String> params,
String encode) throws Exception {
PostMethod method = new PostMethod(urlString);
try {
Set<String> keys = params.keySet();
NameValuePair[] values = new NameValuePair[keys.size()];
int i = 0;
for (String key : keys) {
NameValuePair v = new NameValuePair();
v.setName(key);
v.setValue(params.get(key));
values[i] = v;
i++;
}
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(urlString, 80, "http");
if (!"".equals(encode) && encode != null)
client.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, encode);
method.setRequestBody(values); // 使用 POST 方式提交数据
int state = client.executeMethod(method); // 返回的状态
if (state != HttpStatus.SC_OK) {
throw new Exception("HttpStatus is " + state);
}
String response = method.getResponseBodyAsString();
if (null != encode && !StringUtils.EMPTY.equals(encode)) {// nul写在前面,避免空指针
response = new String(response.getBytes(encode), encode);
}
return response; // response就是最后得到的结果
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
method.releaseConnection();
}
}