在我的应用程序中,我想拦截所有网络调用,并希望在本机Android应用程序中处理它们。我在回复json对jtml的回应时面临问题。它给出了错误" No' Access-Control-Allow-Origin'标头出现在请求的资源上。"
请在下面找到我的HTML: 函数myCall(){
var request = $.ajax({
url: "http://ip.jsontest.com/",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8"
});
request.done(function(msg) {
alert("Response: " + msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
<meta charset="utf-8" />
<title>My jQuery Ajax test</title>
<style type="text/css">
#mybox {
width: 300px;
height: 250px;
border: 1px solid #999;
}
</style>
</head>
<body>
The following div will be updated after the call:<br />
<div id="mybox"></div>
<input type="button" value="Update" onclick="myCall()"/>
</body>
</html>
这是我的shouldInterceptLoadRequest方法:
public WebResourceResponse shouldInterceptLoadRequest(WebView, String url) {
if(url.startsWith("http://ip")){
SNAPIRequestModel apiModel = new SNAPIRequestModel(url);
apiModel.setRequestType(SNConstants.GET_REQUEST);
apiModel.setMethodCallType(SNConstants.SYNCHRONOUS_CALL);
//invoke the core data manager to get the data from network
Object response = ... //fetching response
if(response!=null) {
try {
JSONObject data = ((JSONObject) response);
System.out.print(data.toString());
InputStream stream = new ByteArrayInputStream(data.toString().getBytes("UTF-8"));
return new WebResourceResponse("application/json;", "UTF-8", stream);
} catch (UnsupportedEncodingException ex) {
}
}
}
return super.shouldInterceptLoadRequest(view, url);
}