I'm trying to execute an internal http: GET from a VF page on a Knowledge Article so that I can parse the response HTML for some text in the page. (The Knowledge article looks like this: https://cs7.salesforce.com/articles/FAQ/Test-Article-1)
So my problem is that if I do an http GET on the Original VisualForce URL: 'https://c.cs7.visual.force.com/articles/FAQ/Test-Article-1' then I will be redirected to: 'https://cs7.salesforce.com/articles/FAQ/Test-Article-1'
However, if I do an http GET on the second URL, I am returned with the Salesforce login page. Apparently, my sessionId isn't valid there. How can I retrieve the body of the second URL while I'm authenticated within visualforce?
Thanks for any help, DaveS
Here's my code:
public String getResponseBody(String originalUrl) {
originalUrl ='https://c.cs7.visual.force.com/articles/FAQ/Test-Article-1';
Boolean redirect = false;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(originalUrl);
req.setMethod('GET');
req.setHeader('Authorization','Bearer '+UserInfo.getSessionId());
req.setHeader('Cookie','sid='+UserInfo.getSessionId()); // Not sure this is necessary
HttpResponse res = h.send(req);
//Redirection checking
if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
do {
redirect = false; // reset the value each time
String loc = res.getHeader('Location'); // get location of the redirect
if(loc == null) {
redirect = false;
break;
}
req = new HttpRequest();
req.setEndpoint(loc);
req.setMethod('GET');
req.setHeader('Authorization','Bearer '+UserInfo.getSessionId());
req.setHeader('Cookie','sid='+UserInfo.getSessionId());
res = h.send(req);
if(res.getStatusCode() != 500) { // 500 = fail
if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
redirect= true;
}
}
} while (redirect && Limits.getCallouts() != Limits.getLimitCallouts());
}
//congratulations you're outside of the redirects now
return res.getBody();
}