[SalesForce] HTTP Post with redirect(302 Response Code auto ridirect to external URL)

I am accessing an Exteranl API, This Api returns the response code as "302" with HTML Response, This what iam expecting to achive, When i got the response as HTML it should redirect to the Response Page.

Below is my apex class

public with sharing class CreateSalesOrder {
private Boolean Failed = false;
private Integer responseCode;  
private String leadId;
Private String AtlasUserToken;
Private String locationHeader; 
public string ResponseLocation;
//Private HttpResponse responseBody;

public CreateSalesOrder(ApexPages.StandardController controller) {
    Http h = new Http();
    String url ='https://abc.com/salesforce/api';
    //String  ids='00Qm0000009MQpnEAG';        
    this.leadId =  ApexPages.currentPage().getParameters().get('ID');
    HttpRequest  req = buildWebServiceRequest(url,  this.leadId);
    HttpResponse  res = invokeWebService(h,req);
    System.Debug('RESPONSE: ' + res.getBody().trim());   
    System.debug('HTTP Response Code: ' + res.getStatusCode());
    System.debug('Response Body: ' + res.getBody());   
    System.debug('Response location: ' + res.getHeader('Location'));   
    responseCode=res.getStatusCode();        
    ResponseLocation= res.getHeader('Location');
    // responseBody.getBody(); 
    //responseCode == 303;
    if (responseCode == 302){  
          this.Failed =true; 
    }else{
         this.Failed =false;            
    } 
}    

public HttpRequest buildWebServiceRequest(String url, String ids) {
    //Build HTTP Request object
    JSONGenerator gen = JSON.createGenerator(true);    
    gen.writeStartObject();   
    //UserInfo.getUserId();        
    User u = [select Atlas_User_Token__c from user where id=:userinfo.getuserid()];
    AtlasUserToken = u.Atlas_User_Token__c; 

    String jsonS;
    List <Lead> Leads =  [SELECT Company,FirstName,LastName, Street, City, State, PostalCode, Phone, Email FROM Lead WHERE id=: ApexPages.currentPage().getParameters().get('id')];
    for(Lead c:Leads){
        jsonS = JSON.serialize(
            new Map<String, String> {
                'companyName' => c.Company,
                    'firstName' => c.FirstName,
                    'lastName' => c.LastName,
                    'key' => 'fsdfdsfdsfsekZCbFJ3SU9EbUxLZHfdsdfdsfdsfds'
                    });


    }       
    //  gen.writeEndObject();        
    //String jsonS = gen.getAsString();

    // Sending the http body with JSON 
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json;charset=UTF-8');
    req.setHeader('Accept', 'text/html');
    req.setbody(jsonS); 
    System.debug(req);
    return req;
}    

public HttpResponse invokeWebService(Http h, HttpRequest req) {
    //Invoke Web Service
    HttpResponse res = h.send(req); 
    return res;        
}

public PageReference getRedir() {  
    HttpRequest  req;
    HttpResponse  res;
    if (!this.Failed) {
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got '+ responseCode + ' error Response from atlas. Please Contact System Administrator or try again later.'));
        return null;
    } else {       
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got '+ responseCode + ' error Response from atlas. Please Contact System Administrator or try again later.'));
        PageReference newPage = new PageReference(ResponseLocation);
        newPage.setRedirect(true);
        return newPage;             
    }

}

private final ApexPages.StandardController controller;
}

This api "https://abc.com/salesforce/api" behave like this, If we post the request Json to that API,it will authenticate key and redirect to https://abc.com(User authentication happen and logged-in to that page ).

In my above code, Redirect HTTP response code and then grabs the location from the headers but its redirection to sign in page.

Best Answer

Its because you are authenticating in APEX and then when redirecting in your Browser, Your browser isn't authenticated and hence it asks you to login. Apex and browser both are different systems. Apex runs on SF server, and redirection works on your local machine. As there is no exchange of session information from apex to browser it treats the new redirect request as unauthenticated.

I dont know what that external system you are using, but if you have authkey/session ID you can login to that url.

eg: in SF you can login directly using session id as

https://<endpoint host>/secur/frontdoor.jsp?sid=<session id>

additionally you can specify the return url it will redirect after successful login as startURL

 https://<endpoint host>/secur/frontdoor.jsp?sid=<session id>&startURL=%2F003

The above code will redirect to contact list view after login.

Src: https://developer.salesforce.com/forums/?id=906F00000008oy0IAA