ajax发送请求跨域
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:52
问题:ajax发送请求出现cors跨域
解决办法:可以通过java代理的方式,后台发送请求
1.get请求
public void proxyGet(String url) {
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Connection", "Keep-Alive");
// 建立实际的连接
connection.connect();
InputStream inStream = connection.getInputStream();
OutputStream stream = response.getOutputStream();
stream.write(GetInputStream(inStream)); //上传参数
stream.flush();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2.post请求
public String proxyPost(String url, String params) {
String result = null;
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpPost = new HttpPost(url);
// 设置通用的请求属性
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
// 往服务器里面发送数据
StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
httpPost.setEntity(entity);
// 建立实际的连接
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
System.out.println("请求返回状态:"+status.getStatusCode());
// 获取返回数据
if (status.getStatusCode() == 200) {
HttpEntity responseEntity = response.getEntity();
result= EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
相关文章
-
ajax接收json
ajax接收json
- 互联网
- 2026年04月04日
-
Ajax接收json响应
Ajax接收json响应
- 互联网
- 2026年04月04日
-
Ajax前台返回JSON数据后再Controller中直接转换成类型使用,后台接收json转成实体的方法
Ajax前台返回JSON数据后再Controller中直接转换成类型使用,后台接收json转成实体的方法
- 互联网
- 2026年04月04日
-
AJAX发送json,SpringMVC 接收JSON,@RequestBody
AJAX发送json,SpringMVC 接收JSON,@RequestBody
- 互联网
- 2026年04月04日
-
AI探索(四)NumPy库的使用
AI探索(四)NumPy库的使用
- 互联网
- 2026年04月04日
-
AI加持的阿里云飞天大数据平台技术揭秘
AI加持的阿里云飞天大数据平台技术揭秘
- 互联网
- 2026年04月04日






