After researching more about the problem I came to know that problem is because my requests are Cross-Domain and browser can't allow such requests due to security. Because if that is allowed Internet security will be insane to handle. I found a very good post which explained everything in detail.
I tried using JQuery, JavaScript everything even the JSONP requests were not working since I had no access to the other server. So I used the solution of Server Side call in my code. In Short I did following things
- Created a new Servlet (This is the only servlet in my demo project if you have existing servelt you can just add a new case).
Inside the processRequest method added call to the second server (third party).
protected void processRequest(HttpServletRequest request, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
httpServletResponse.setContentType("image/png");
String url = "http://www.w3schools.com/angular/pic_angular.jpg";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedInputStream in = new BufferedInputStream(con.getInputStream());
byte[] imageArray = new byte[1024];
StringBuilder response = new StringBuilder();
BufferedOutputStream bout = new BufferedOutputStream(httpServletResponse.getOutputStream());
while ((in.read(imageArray)) != -1) {
bout.write(imageArray);
}
System.out.println(response.toString());
in.close();
bout.close();
}
Instead of calling directly third party server my Angular now calls my own server, see JS code below
var iFrameDemo = angular.module("iFrameDemo", []);
iFrameDemo.controller("iFrameDemoController", function ($scope, $sce, $http) {
url = "/webApp/controller";
$scope.iframesrcurl = url;
console.log('iframesrcurl is ' + $scope.iframesrcurl);
// url = 'http://www.w3schools.com/angular/pic_angular.jpg?&callback=JSON_CALLBACK';
$scope.desiredFrameSource = url;
$scope.errorImageSrc = '/webApp/images/thumb_down-512.png';
var responsePromise = $http.get(url);//'http://localhost:8084/iframe/newLogin.html');
responsePromise.success(function (data) {
console.log("AJAX call was success " + data.found);
$scope.iframesrcurl = $sce.trustAsResourceUrl(url);
});
responsePromise.error(function () {
console.log("AJAX call failed");
$scope.iframesrcurl = $scope.errorImageSrc;
});});
Declared Iframe in JSP file as
<iframe ng-src="{{iframesrcurl}}" frameborder="0" width="100%" height="1100px" scrolling="auto" onload="iframeContentLoaded();" onerror="onerrorLoadingiFrame();">
<h3>No such page</h3>
</iframe>
That was it.. It worked like a charm than.. Please feel free to post if you have a better alternative to this. Hope this approach too helps someone..