I've been trying to get the top news story from Hacker News, though an example from any website would do.
Here is my code by the way:
let getHTML = function (url, callback) {
// Feature detection
if (!window.XMLHttpRequest) return;
// Create new request
let xhr = new XMLHttpRequest();
// Setup callback
xhr.onload = function () {
if (callback && typeof (callback) === 'function') {
callback(this.responseXML);
}
};
// Get the HTML
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
getHTML('https://news.ycombinator.com/news', function (response) {
let someElem = document.querySelector('#someElementFromMyPage');
let someOtherElem = response.querySelector('#someElementFromOtherPage');
someElem.innerHTML = someOtherElem.innerHTML;
});
This should display the element from other page and bring it to my page.
When I run your code, I get a CORS error in the browser dev-tools console (more details here).
Problem
Basically the target website (https://news.ycombinator.com/news) is restricting how a Browser can request it. And the browser conforms and respects this restriction.
The JS code makes the request.
The browser reads the response and looks at the HTTP headers included in the response from (https://news.ycombinator.com/news)
Because there's X-Frame-Options: DENY and X-XSS-Protection: 1 mode=block the browser won't let you read the request in the JS code, so you get an error.
Solution
There's many options for getting around CORS errors, you can research them yourself:
Funnel requests through a proxy-server, routing CORS requests through another server that strips off the pesky CORS headers. maybe this?
Run a server for web-scraping, servers don't have to respect Headers like the browser does, so you can GET anything. maybe try this
Scraping within the browser is increasingly hard, so you need to use other solutions to take content from other sites.
Hope this helps!
How do I access a page's HTTP response headers via JavaScript?
Related to this question, which was modified to ask about accessing two specific HTTP headers.
Related:
How do I access the HTTP request header fields via JavaScript?
It's not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.
Use the following JavaScript code to get all the HTTP headers by performing a get request:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.
myXMLHttpRequest.getAllResponseHeaders();
The API was specified in the following candidate recommendation for XMLHttpRequest: XMLHttpRequest - W3C Candidate Recommendation 3 August 2010
Specifically, the getAllResponseHeaders() method was specified in the following section: w3.org: XMLHttpRequest: the getallresponseheaders() method
The MDN documentation is good, too: developer.mozilla.org: XMLHttpRequest.
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};
//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
2. Make Inferences
There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
3. Stash them
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.
Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.
Best case is to just do a HEAD request and then examine the headers.
For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html
Just my 2 cents.
A solution with Service Workers
Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.
How it works:
Add a service worker on your website.
Watch every request that's being sent.
Make the service worker fetch the request with the respondWith function.
When the response arrives, read the headers.
Send the headers from the service worker to the page with the postMessage function.
Working example:
Service workers are a bit complicated to understand, so I've built a small library that does all this. It is available on github: https://github.com/gmetais/sw-get-headers.
Limitations:
the website needs to be on HTTPS
the browser needs to support the Service Workers API
the same-domain/cross-domain policies are in action, just like on XMLHttpRequest
Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.
(2021) An answer without additional HTTP call
While it's not possible in general to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can't be exposed easily in any other way than via a header:
You may use Server-Timing header to expose arbitrary key-value data, and it will be readable by JavaScript.
(*in supported browsers: Firefox 61, Chrome 65, Edge 79; no Safari yet and no immediate plans for shipping as of 2021.09; no IE)
Example:
server-timing: key;desc="value"
You can use this header multiple times for multiple pieces of data:
server-timing: key1;desc="value1"
server-timing: key2;desc="value2"
or use its compact version where you expose multiple pieces of data in one header, comma-separated.
server-timing: key1;desc="value1", key2;desc="value2"
Example of how Wikipedia uses this header to expose info about cache hit/miss:
Code example (need to account for lack of browser support in Safari and IE):
if (window.performance && performance.getEntriesByType) { // avoid error in Safari 10, IE9- and other old browsers
let navTiming = performance.getEntriesByType('navigation')
if (navTiming.length > 0) { // still not supported as of Safari 14...
let serverTiming = navTiming[0].serverTiming
if (serverTiming && serverTiming.length > 0) {
for (let i=0; i<serverTiming.length; i++) {
console.log(`${serverTiming[i].name} = ${serverTiming[i].description}`)
}
}
}
}
This logs cache = hit-front in supported browsers.
Notes:
as mentioned on MDN, the API is only supported over HTTPS
if your JS is served from another domain, you have to add Timing-Allow-Origin response header to make the data readable to JS (Timing-Allow-Origin: * or Timing-Allow-Origin: https://www.example.com)
Server-Timing headers support also dur(header) field, readable as duration on JS side, but it's optional and defaults to 0 in JS if not passed
regarding Safari support: see bug 1 and bug 2 and bug 3
You can read more on server-timing in this blog post
Note that performance entries buffers might get cleaned by JS on the page (via an API call), or by the browser, if the page issues too many calls for subresources. For that reason, you should capture the data as soon as possible, and/or use PerformanceObserver API instead. See the blog post for details.
For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"], I've created a function parseHttpHeaders:
function parseHttpHeaders(httpHeaders) {
return httpHeaders.split("\n")
.map(x=>x.split(/: */,2))
.filter(x=>x[0])
.reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do: headers["content-type"]
You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".
I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.
Like many people I've been digging the net with no real answer :(
I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.
case ".html":
response.setHeader("Content-Type", "text/html");
response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
// process the real contend of my page
Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]
On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile
// Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
var corsbypass = true;
if (location['GPSD_HTTP_AJAX']) corsbypass = false;
if (corsbypass) { // Json & html served from two different web servers
var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
} else { // Json & html served from same web server [no ?jsoncallback=]
var gpsdApi = "geojson.rest?";
}
var gpsdRqt =
{key :123456789 // user authentication key
,cmd :'list' // rest command
,group :'all' // group to retreive
,round : true // ask server to round numbers
};
$.getJSON(gpsdApi,gpsdRqt, DevListCB);
For who ever would like to check my code:
https://www.npmjs.org/package/gpsdtracking
Allain Lalonde's link made my day.
Just adding some simple working html code here.
Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.
<!DOCTYPE html>
<title>(XHR) Show all response headers</title>
<h1>All Response Headers with XHR</h1>
<script>
var X= new XMLHttpRequest();
X.open("HEAD", location);
X.send();
X.onload= function() {
document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
}
</script>
Note: You get headers of a second request, the result may differ from the initial request.
Another way is the more modern fetch() API
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Per caniuse.com it's supported by Firefox 40, Chrome 42, Edge 14, Safari 11
Working example code:
<!DOCTYPE html>
<title>fetch() all Response Headers</title>
<h1>All Response Headers with fetch()</h1>
<script>
var x= "";
if(window.fetch)
fetch(location, {method:'HEAD'})
.then(function(r) {
r.headers.forEach(
function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
);
})
.then(function() {
document.body.appendChild(document.createElement("pre")).textContent= x;
});
else
document.write("This does not work in your browser - no support for fetch API");
</script>
If we're talking about Request headers, you can create your own headers when doing XmlHttpRequests.
var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);
To get the headers as an object which is handier (improvement of Raja's answer):
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
if (b.length) {
var [ key, value ] = b.split(': ');
a[key] = value;
}
return a;
}, {});
I've just tested, and this works for me using Chrome Version 28.0.1500.95.
I was needing to download a file and read the file name. The file name is in the header so I did the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
success(xhr.response); // the function to proccess the response
console.log("++++++ reading headers ++++++++");
var headers = xhr.getAllResponseHeaders();
console.log(headers);
console.log("++++++ reading headers end ++++++++");
}
};
Output:
Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream
This is my script to get all the response headers:
var url = "< URL >";
var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send(null);
var headers = req.getAllResponseHeaders();
//Show alert with response headers.
alert(headers);
Having as a result the response headers.
This is a comparison test using Hurl.it:
Using mootools, you can use this.xhr.getAllResponseHeaders()
This is an old question. Not sure when support became more broad, but getAllResponseHeaders() and getResponseHeader() appear to now be fairly standard: http://www.w3schools.com/xml/dom_http.asp
As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.
In Express, for example, the following works:
app.get('/somepage', (req, res) => {
res.render('somepage.hbs', {headers: req.headers});
})
The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.
I think the question went in the wrong way,
If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header.
Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..
I am attempting to download a file from Google Storage using the Javascript json api. I am able to retreive the object info by using the code below, however I'm not sure how to get the actual media. I'm familiar with the Java library method getMediaHttpDownloader, but I do not see an equivalent in JS. Any help would be appreciated!
gapi.client.storage.objects.get({"bucket":"bucketName","object":"objectName"});
The Javascript library does not currently support directly downloading media. You can still get to the data, but you'll have to access it another way.
Depending on the domain your website is hosted on and the bucket you're reading from, you'll need to set up CORS: https://developers.google.com/storage/docs/cross-origin
Then, you'll need to request the object directly via the XML API. For example, you could do something like this:
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://'+bucket+'.storage.googleapis.com/'+object);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
I've ended up not using the api(not sure that you can download using api, interested if you do know how) and using XmlHttpRequest instead. To do this I had to setup CORS for my google storage bucket to allow my site cross domain access. Below is my code:
var myToken = gapi.auth.getToken();
var req = new XMLHttpRequest;
req.open('GET','https://storage.googleapis.com/bucket/object',
true);
req.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
req.send(null);
I did it using gapi and jQuery.
In my case object is public. (pulbic link in storage browser must be checked). In case you don't want your object to be public, use $.post instead of $.get and provide assess_token as header exactly as it is done in other answers.
Storage.getObjectInfo retrieves object metadata.
Storage.getObjectMedia retrieves object content.
var Storage = function() {};
Storage.bucket = 'mybucket';
Storage.object = 'myfolder/myobject'; //object name, got by gapi.objects.list
Storage.getObjectMedia = function(object, callback) {
function loadObject(objectInfo) {
var mediaLink = objectInfo.mediaLink;
$.get(mediaLink, function(data) { //data is actually object content
console.log(data);
callback(data);
});
}
Storage.getObjectInfo(object, loadObject);
};
Storage.getObjectInfo = function(object, callback) {
var request = gapi.client.storage.objects.get({
'bucket' : Storage.bucket,
'object' : Storage.object
});
request.execute(function(resp) {
console.log(resp);
callback(resp);
});
};
It is also relatively rare case when we need to download the content of object. In most cases objects stored in Storage are media files like images and sounds and then all what we need is actually mediaLink, which must be inserted to src attribute value of appropriate dom element (img or audio).
I'm loading a motion jpeg from third-party site, which I can trust. I'm trying to getImageData() but the browser (Chrome 23.0) complains that:
Unable to get image data from canvas because the canvas has been tainted by
cross-origin data.
There are some similar questions on SO, but they are using local file and I'm using third party media. My script runs on a shared server and I don't own the remote server.
I tried img.crossOrigin = 'Anonymous' or img.crossOrigin = '' (see this post on the Chromium blog about CORS), but it didn't help. Any idea on how can I getImageData on a canvas with cross-origin data? Thanks!
You cannot reset the crossOrigin flag once it is tainted, but if you know before hand what the image is you can convert it to a data url, see Drawing an image from a data URL to a canvas
But no, you cannot and should not be using getImageData() from external sources that don't support CORS
While the question is very old the problem remains and there is little on the web to solve it. I came up with a solution I want to share:
You can use the image (or video) without the crossorigin attribute set first and test if you can get a HEAD request thru to the same resource via AJAX. If that fails, you cannot use the resource. if it succeeds you can add the attribute and re-set the source of the image/video with a timestamp attached which reloads it.
This workaround allows you to show your resource to the user and simply hide some functions if CORS is not supported.
HTML:
<img id="testImage" src="path/to/image.png?_t=1234">
JavaScript:
var target = $("#testImage")[0];
currentSrcUrl = target.src.split("_t=").join("_t=1"); // add a leading 1 to the ts
$.ajax({
url: currentSrcUrl,
type:'HEAD',
withCredentials: true
})
.done(function() {
// things worked out, we can add the CORS attribute and reset the source
target.crossOrigin = "anonymous";
target.src = currentSrcUrl;
console.warn("Download enabled - CORS Headers present or not required");
/* show make-image-out-of-canvas-functions here */
})
.fail(function() {
console.warn("Download disabled - CORS Headers missing");
/* ... or hide make-image-out-of-canvas-functions here */
});
Tested and working in IE10+11 and current Chrome 31, FF25, Safari 6 (Desktop).
In IE10 and FF you might encounter a problem if and only if you try to access http-files from a https-script. I don't know about a workaround for that yet.
UPDATE Jan 2014:
The required CORS headers for this should be as follows (Apache config syntax):
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "referer, range, accept-encoding, x-requested-with"
the x-header is required for the ajax request only. It's not used by all but by most browsers as far as I can tell
Also worth noting that the CORS will apply if you are working locally regardless of if the resource is in the same directory as the index.html file you are working with. For me this mean the CORS problems disappeared when I uploaded it to my server, since that has a domain.
You can use base64 of the image on canvas,
While converting into base64 you can use a proxy URL (https://cors-anywhere.herokuapp.com/) before your image path to avoid cross-origin issue
check full details here
https://stackoverflow.com/a/44199382/5172571
var getDataUri = function (targetUrl, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyUrl + targetUrl);
xhr.responseType = 'blob';
xhr.send();
};
getDataUri(path, function (base64) {
// base64 availlable here
})
Can I control the HTTP headers sent by window.open (cross browser)?
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks.
Can I control the HTTP headers sent by window.open (cross browser)?
No
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
You can request a URL that triggers a server side program which makes the request with arbitrary headers and then returns the response
You can run JavaScript (probably saying goodbye to Progressive Enhancement) that uses XHR to make the request with arbitrary headers (assuming the URL fits within the Same Origin Policy) and then process the result in JS.
I need some cunning hacks...
It might help if you described the problem instead of asking if possible solutions would work.
Sadly you can't control headers when doing window.open()
Nice and easy, how I managed to open a file with custom headers:
const viewFile = async (url) => {
// Change this to use your HTTP client
fetch(url, {/*YOUR CUSTOM HEADER*/} ) // FETCH BLOB FROM IT
.then((response) => response.blob())
.then((blob) => { // RETRIEVE THE BLOB AND CREATE LOCAL URL
var _url = window.URL.createObjectURL(blob);
window.open(_url, "_blank").focus(); // window.open + focus
}).catch((err) => {
console.log(err);
});
};
Download file to cache
window.open to cache
If you are in control of server side, it might be possible to set header value in query string and send it like that?
That way you could parse it from query string if it's not found in the headers.
Just an idea... And you asked for a cunning hack :)
As the best anwser have writed using XMLHttpResponse except window.open, and I make the abstracts-anwser as a instance.
The main Js file is download.js Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
You can also use an F5 load balancer, and map the cross-browser URL that you are trying to fetch to an URL inside your domain of origin.
Mapping can be something like:
companyA.com/api/of/interest----> companyB.com/api/of/interest
Assuming your domain of origin is "companyA.com" then the browser will not have any problems in sending all cookies on the header of that request, since it's towards the same domain.
The request hits the load balancer and is forwarded towards "companyB.com" with all headers responses will be sent to the from server side.
You can't directly add custom headers with window.open() in popup window
but to work that we have two possible solutions
Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in<i>window.open()</i>
here is abc.html
$.ajax({
url: "ORIGIONAL_URL",
type: 'GET',
dataType: 'json',
headers: {
Authorization : 'Bearer ' + data.id_token,
AuthorizationCheck : 'AccessCode ' +data.checkSum ,
ContentType :'application/json'
},
success: function (result) {
console.log(result);
},
error: function (error) {
} });
call html
window.open('*\abc.html')
here CORS policy can block the request if CORS is not enabled in requested URL.
You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.
Suppose in Java Servlet(/requestURL) we'll make this request
`
String[] responseHeader= new String[2];
responseHeader[0] = "Bearer " + id_token;
responseHeader[1] = "AccessCode " + checkSum;
String url = "ORIGIONAL_URL";
URL obj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Authorization", responseHeader[0]);
urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
}
in.close();
response.sendRedirect(response1.toString());
// print result
System.out.println(response1.toString());
} else {
System.out.println("GET request not worked");
}
`
call servlet in window.open('/requestURL')
Use POST instead
Although it is easy to construct a GET query using window.open(), it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:
<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>
<input type="button" onclick="loadNnextPage()" value="Click me!">
<script>
function loadNnextPage() {
document.getElementById("helper").headerData.value = "New";
document.getElementById("helper").submit();
}
</script>
Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.
Problems with GET
Query strings get stored in browser history,
can be shoulder-surfed
copy-pasted,
and often you don't want it to be easy to "refresh" the same transaction.