/**
* HTTP-post 请求
* @param url
* @param params
* @return
* @throws HttpException
* @throws InterruptedException
*/
public static String post(String url, Map<String, String> params) throws HttpException, InterruptedException {
String body = "";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,1000*5);
// 读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*60);
HttpPost post = postForm(url, params);
HttpResponse response = httpclient.execute(post);
body = paseResponse(response);
}catch (ConnectTimeoutException e) {
logger.info("post 发送异常:",e);
}catch(SocketTimeoutException e){
logger.info("post 发送异常:",e);
} catch (Exception e) {
logger.info("post 发送异常:",e);
}finally{
httpclient.getConnectionManager().shutdown();
}
return body;
}
/**
* 封装参数
* @param url
* @param params
* @return
* @throws URISyntaxException
*/
private static HttpPost postForm(String url, Map<String, String> params) throws URISyntaxException{
HttpPost httpost = new HttpPost(url);
try {
logger.debug("开始执行postForm");
int n = params.size();
NameValuePair[] nvps =new NameValuePair[n];
int j = 0;
Set<String> keySet = params.keySet();
for(String key : keySet) {
nvps[j] = (new BasicNameValuePair(key, params.get(key)));
if(j<n)
j++;
}
logger.debug("执行中postForm"+nvps.length);
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
logger.info("HTTP拼装参数异常:",e);
}
return httpost;
}
/**
* 响应
* @param response
* @return
*/
private static String paseResponse(HttpResponse response) {
HttpEntity entity = response.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
logger.info("POST-method type="+charset);
String body = "";
try {
body = EntityUtils.toString(entity);
logger.info("POST-method Response="+body);
} catch (ParseException e) {
logger.info("Response-error=",e);
} catch (IOException e) {
logger.info("Response-error=",e);
}
return body;
}
// public static String get(String url) throws URISyntaxException, HttpException, InterruptedException {
// DefaultHttpClient httpclient = new DefaultHttpClient();
// String body = null;
//
// HttpGet get = new HttpGet(url);
// body = invoke(httpclient, get);
//
// httpclient.getConnectionManager().shutdown();
//
// return body;
// }