1、先看一个网站介绍,了解跨域问题    HTTP访问控制(CORS)

2、像谷歌、火狐浏览器对一些非简单请求会触发预检请求,首先使用 OPTIONS   方法发起一个预检请求到服务器,然而IE浏览器没有预检请求

3、发起预检请求,如果想要后台处理成功,那么就需要服务器处理返回响应,设置允许的请求头,设置允许跨域等(对WebService研究较浅,没有找到对预检请求设置的方法,后期会深入学习)

4、在测试中使用谷歌,如果不设置contenttype,默认为 text/plain;charset=UTF-8或application/x-www-form-urlencoded,更改为其他两个都不会触发预检请求

5、谷歌浏览器ajax设置contenttype为text/xml时,对JDK发布的WebService和CXF发布的WebService错误显示如下

JDK发布的WebService服务

1)后台报错、找到com.sun.xml.internal.ws.transport.http.server.WSHttpHandler这个类,在handle方法处打断点,可以在参数中看到请求的信息,method为options;然后运行完控制台报错(使用IE就没事)

com.sun.xml.internal.ws.transport.http.server.WSHttpHandler handleExchange
警告: Cannot handle HTTP method: OPTIONS

这就是浏览器的预检请求导致,网上有设置如果检测到请求方法是OPTIONS就设置返回状态为200

2)前台报错、console下报错:OPTIONS http://localhost:8088/aaa net::ERR_EMPTY_RESPONSE

然后在network下找到发送的ajax请求,点击,Request Headers有警告Provisional headers are shown

正常情况下请求头会显示一些其他信息如Accept-Language、Accept-Encoding等

3)ajax不设置contenttype、请求后台就报错

Unsupported Content-Type: text/plain;charset=UTF-8 Supported ones are: [text/xml]
com.sun.xml.internal.ws.server.UnsupportedMediaException: Unsupported Content-Type: text/plain;charset=UTF-8 Supported ones are: [text/xml]

也就是建议设置Content-Type为text/xml;但是设置成text/xml就会触发预检测

前台Console报错   No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8083' is therefore not allowed access. The response had HTTP status code 415.估计是后台异常,没有设置响应头非同源访问的权限

此处可以看到请求头默认Content-Type为text/plain;charset=UTF-8

CXF发布的WebService服务

1)、后台报错、找到类org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor断点到handleMessage方法,查看message参数

后台报错

Interceptor for {http://server.hjp.com/}PersonService1Service has thrown exception, unwinding now
org.apache.cxf.binding.soap.SoapFault: Error reading XMLStreamReader.

可见也是预检测请求导致

2)前端报错:OPTIONS http://localhost:5555/hello 500 (Server Error)和Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.  network中的ajax请求头中没有Content-Type

3)如果去掉ajax对contenttype设置,前端会报错No 'Access-Control-Allow-Origin' header is present on the requested resource

6、ajax请求WebService代码(使用IE访问没问题)

1)、jQuery形式

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="d"></div>
<script type="text/javascript">
$.ajax({
url: "http://localhost:5555/hello",
type: "POST",
contentType:"text/xml;charset=UTF-8",
data: getPostData(),
success: function (data) {
var doc = $(data).find('return');
doc.each(function(){
$('#d').html($(this).text());
});
}
});
//定义满足SOAP协议的参数。
function getPostData() {
var soap='<?xml version="1.0" encoding="UTF-8"?>'+
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://server.hjp.com/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<ser:sayHello>' +
'<arg0>aaa</arg0>' +
'</ser:sayHello>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
return soap;
}
</script>
</body>
</html>

2)、原生Ajax形式

<html>
<head>
<meta charset="UTF-8"/>
<title>通过ajax调用WebService服务</title>
<script>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest){
//非ie浏览器
xhr = new XMLHttpRequest();
}else{
//ie浏览器
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
return xhr;
}
var xhr =getXhr();
function sendMsg(){
var name = document.getElementById('name').value;
//服务的地址
var wsUrl = 'http://localhost:8088/tongwei'; //请求体
var soap=getPostData(name); //打开连接
xhr.open('POST',wsUrl,true); //重新设置请求头
xhr.setRequestHeader("content-type","text/xml"); //设置回调函数
xhr.onreadystatechange = _back; //发送请求
xhr.send(soap);
} function _back(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var ret = xhr.responseXML;
var msg = ret.getElementsByTagName('return')[0];
document.getElementById('showInfo').innerHTML = msg.textContent;
}
}
}
//定义满足SOAP协议的参数。
function getPostData(name) {
var postdata ='<?xml version="1.0" encoding="UTF-8"?>'+
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ton="http://tongwei/">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<ton:test>' +
'<parStr>'+name+'</parStr>' +
'</ton:test>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
return postdata;
}
</script>
</head>
<body>
<input type="button" value="发送SOAP请求" onclick="sendMsg();">
<input type="text" id="name">
<div id="showInfo">
</div>
</body>
</html>

7、java后台URL请求WebService方式

public static void main(String[] args) throws IOException {

          /*
*1.创建一个url
*2.打开一个连接
*3.设置相关参数
*4.创建输出流,用来发送SAOP请求
*5.发送完,接收数据
*6.用输入流获取webservice中的内容
*/ URL url = new URL("http://localhost:5555/hello");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");//必须设置为POST方式,而且必须是大写的
connection.setDoInput(true);//因为有输入参数也有输出参数所以都为真
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); OutputStream out = connection.getOutputStream();
//下面替换尖括号是测试传送xml文本字符串测试的
//String str="<list><item><email>aaa!qq</email></item></list>";
//str=str.replaceAll("<","&lt;").replaceAll(">","&gt;");
StringBuilder soap=new StringBuilder();
soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://server.hjp.com/\">");
soap.append("<soapenv:Header/>");
soap.append("<soapenv:Body>");
soap.append("<ser:sayHello>");
soap.append("<arg0>aaa</arg0>");
soap.append("</ser:sayHello>");
soap.append("</soapenv:Body>");
soap.append("</soapenv:Envelope>");
String argo=soap.toString();
System.out.println(argo);
out.write(argo.getBytes());//发送SAOP请求
InputStream stream = connection.getInputStream();
byte[] b = new byte[1024];
int len=0;
StringBuffer buffer = new StringBuffer();
while((len=stream.read(b))!=-1){
String s = new String(b, 0, len, "utf-8");
buffer.append(s);
} System.out.println(buffer.toString()); }

8、请求头和响应头编写及处理返回值是借助SOAPUI工具,界面如下

ajax访问WebService跨域问题的更多相关文章

  1. Ajax请求WebService跨域问题 [转载]

    1.背景 用Jquery中Ajax方式在asp.net开发环境中WebService接口的调用 2.出现的问题 原因分析:浏览器同源策略的影响(即JavaScript或Cookie只能访问同域下的内容 ...

  2. Ajax请求WebService跨域问题

    1.背景 用Jquery中Ajax方式在asp.net开发环境中WebService接口的调用 2.出现的问题 原因分析:浏览器同源策略的影响(即JavaScript或Cookie只能访问同域下的内容 ...

  3. ajax调用webservice 跨域问题

    用js或者jquery跨域调用接口时 对方的接口需要做jsonp处理,你的ajax jsonp调用才可以 egg 接口中已经做了jsonp处理,所以可以跨域调用 //$.ajax({ // url: ...

  4. ajax 调用webservice 跨域问题

    注意两点 1. 在webservice的config中加入这段位置 (注意不是调用webservice的webconfig中加入) <system.webServer>     <! ...

  5. JS-JQuery(JSONP)调用WebService跨域若干技术点

    1.JSONP:JSON With Padding,让网页从别的网域获取信息,也就是跨域获取信息,可以当做是一种“工具”,大多数架构Jquery.EXTjs等都支持. 由于同源策略,一般来说位于 se ...

  6. js中ajax如何解决跨域请求

    js中ajax如何解决跨域请求,在讲这个问题之前先解释几个名词 1.跨域请求 所有的浏览器都是同源策略,这个策略能保证页面脚本资源和cookie安全 ,浏览器隔离了来自不同源的请求,防上跨域不安全的操 ...

  7. Ajax【介绍、入门、解决Ajax中文、跨域、缓存】

    什么是Ajax Ajax(Asynchronous JavaScript and XML) 异步JavaScript和XML Ajax实际上是下面这几种技术的融合: (1)XHTML和CSS的基于标准 ...

  8. 06: AJAX全套 & jsonp跨域AJAX

    目录: 1.1 AJAX介绍 1.2 jQuery AJAX(第一种) 1.3 原生ajax(第二种) 1.4 iframe“伪”AJAX(第三种) 1.5 jsonp跨域请求 1.6 在tornad ...

  9. ajax请求ashx跨域问题解决办法

    ajax请求ashx跨域问题解决办法 https://blog.csdn.net/windowsliusheng/article/details/51583566 翻译windowsliusheng  ...

随机推荐

  1. Centos warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory

    vi /etc/environment add these lines... LANG=en_US.utf-8 LC_ALL=en_US.utf-8 QQ技术交流群:576269252 ------- ...

  2. MySQL递归查询树状表的子节点、父节点

    表结构和表数据就不公示了,查询的表user_role,主键是id,每条记录有parentid字段; 如下mysql查询函数即可实现根据一个节点查询所有的子节点,根据一个子节点查询所有的父节点.对于数据 ...

  3. PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization

    用卷积神经网络对相机位置和角度进行回归.

  4. Ogre2.1 结合OpenGL3+高效渲染

    在DX10与OpenGL3+之前,二者都是固定管线与可编程管线的混合,其中对应Ogre1.x的版本,也是结合固定与可编程管线设计.转眼到了OpenGL3+与DX10后,固定管线都被移除了,相对应着色器 ...

  5. PHP + Smarty + html5 构建Wap应用

    一 简介     Smarty是一个PHP编写的模板引擎(template engine),主要用于构建web应用程序的表示层.Smarty的主页是http://www.smarty.net/down ...

  6. JUnit教程

    测试是检查应用程序是否是工作按照要求,并确保在开发者水平,单元测试进入功能性的处理.单元测试是单一实体(类或方法)的测试. 单元测试在每一个软件公司开发高品质的产品给他们的客户是十分必要的. 单元测试 ...

  7. e739. 创建一个标签组件

    // The text is left-justified and vertically centered JLabel label = new JLabel("Text Label&quo ...

  8. Unity----Scene加载问题

    Unity官方提供了4种加载场景(scene)的方法,分别是: 1. Application.LoadLevel():同步加载 2. Application.LoadLevelAsync():异步加载 ...

  9. jQuery使用动态渲染表单功能完成ajax文件下载

    原文链接:http://www.poluoluo.com/jzxy/201301/195126.html 封装的通用js函数代码: // Ajax 文件下载 jQuery.download = fun ...

  10. Enigma Virtual Box:生成可执行文件。

    Enigma Virtual Box Enigma Virtual Box[1]  是软件虚拟化工具,它可以将多个文件封装到应用程序主文件,从而制作成为单执行文件的绿色软件.它支持所有类型的文件格式, ...