java调用webService接口
通过创建下面的方法,调用方法即可,返回值为接收到的xml字符串。
// point webService接口地址 ; params 入参 ,通过soupUI生成的参数,soapAction 可以传空字符""
public static String doPostWebServiceURL(String point, String params, String soapAction)throws Exception {
String result = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(point);
try {
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(params,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (Exception e) {
log.error("调用远程WebService接口异常:{}" , e);
throw e;
}finally {
IOUtils.closeQuietly(closeableHttpClient);
}
return result;
}
java通过POST方法调用http请求
public static String httpPost(String url, String data) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
if (StringUtils.isNotBlank(data)){
StringEntity entity = new StringEntity(data, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
logger.info("HttpUtil.httpPost: url={} "+url+", data={} "+data);
try {
logger.info("HttpUtil.httpPost:" + httpPost.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity responseEntity= httpResponse.getEntity();
String response = EntityUtils.toString(responseEntity, "utf-8");
EntityUtils.consume(responseEntity);
logger.info("请求[" + url + "]返回:" + response);
return response;
} else {
logger.error("fail ---- " + statusCode);
}
} catch (Exception e) {
logger.error("HttpUtil.httPost error :" + e.getMessage(), e);
} finally {
httpPost.releaseConnection();
}
return null;
}
调用:
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("startTime", startTime);
parameters.put("endTime",endTime);
String result = HttpUtils.httpPost(url, JsonMapper.toJsonString(parameters));