今天在开发的时候发现用前端ajax调用其他机器的post接口请求的时候发现一直存在跨域请求问题,本来想用nginx代理解决跨域问题,后来又发现接口又有多个,代理麻烦,后期还要增加,后来就发现可以用java后端调用远程接口,并将返回来的结果返回给页面,这样就完美的解决了,直接赋上工具类
public Class ClientUtil {
/**
* 接口调用
* @param url 接口地址 json 为参数 参考(gson.getInstance.toJson(new HashMap("参数名","参数值")))需要转换 * 成json串格式的
*/
public static String doClient(String url,String json) {
return doPost(url,json);
}
/**
* 获取连接
* @return CloseableHttpClient对象
*/
public CloseableHttpClient buildHttpClient(){
CloseableHttpClient client = null;
HttpClientBuilder build = HttpClients.custom();
client = build.build();
return client;
}
/**
* 进行Post请求
* @param url 服务地址
* @param json 添加json串
* @return String结果
*/
public String doPost(String url,String json){
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(url);
String result = null;
try {
httpPost.setHeader("content-type", "application/json;charset=UTF-8");//
StringEntity se = new StringEntity(json,"utf-8");
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
//logger.error("进行模拟HTTP请求时候发生异常 ,请求地址"+url,e);
} catch (UnsupportedEncodingException e) {
//logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
} catch (Exception e) {
//logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
} finally {
// 关闭连接,释放资源
try {httpClient.close(); }catch (IOException e) {e.printStackTrace(); }
}
return result;
}
}