+ Start a Discussion
PrattyPratty 

Callout Exception

Hello All,

I am trying to integrate with Siebel system, through Apex class generated from wsdl but getting below error,

System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found ':HTML'

When I am executing service end point url in browser it's working(by placing ?wsdl at the end of url), also it is working fine in SOAPUI.
Can you please help me to resolve this?

Thanks in advance.

Regards,
Rudra
Ashish_SFDCAshish_SFDC
Hi Pratty, 


Its telling you that the web service returned an HTML document when it was expecting a soap document.

You'll need to work out why its returning HTML (perhaps there's a firewall/proxy blocking it), perhaps the service threw an exception, and its returning the exception dump error page.

See the links below for related threads, 

https://developer.salesforce.com/forums/ForumsMain?id=906F00000008wHDIAY

https://developer.salesforce.com/forums/ForumsMain?id=906F00000009By5IAE

http://stackoverflow.com/questions/11447494/force-com-callout-is-there-a-way-to-get-the-full-response-from-the-target-serve

http://salesforce.stackexchange.com/questions/22314/while-consuming-webservices-in-salesforce-getting-exception


Regards,
Ashish

PrattyPratty
Accepted as a solution.
SalesforceTechieSalesforceTechie
 @Future(callout=true)
    public static void execute(Set<Id> invoiceIds, String sid) { 
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartObject();
        gen.writeObjectField('invoiceIds', invoiceIds);
        gen.writeEndObject();

        String requestBody = gen.getAsString();

        HttpRequest req = new HttpRequest();
        String remoteSite = System.URL.getSalesforceBaseURL().getHost();
        req.setEndpoint('https://' + remoteSite.toLowerCase()+'/services/apexrest/QUAN/Invoice/XmlWriter');
        req.setMethod('POST');
        req.setTimeout(120000);
        req.setBody(requestBody);

        String authorizationHeader = 'Bearer ' + sid;
        system.debug(authorizationHeader);
        req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type', 'application/json');
        Http http = new Http();
        HTTPResponse res;
        try {
            res = http.send(req);  
            System.debug(res.getBody());
        } catch (Exception e) {
            String msg = 'Invoice submitted but XML data was not created successfully. Invoice records affected: '+invoiceIds;
            strategy_Settings_QUAN__c settings = strategy_Settings_QUAN__c.getInstance();
            String emailAddress = (String)settings.get('SAP_Support_Email_QUAN__c');
            if(String.isBlank(emailAddress)) {
                emailAddress = 'strategy_support_noreply@abcd.com';
            }
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> toAddresses = new List<String>{emailAddress};
            mail.setToAddresses(toAddresses);
            mail.setSubject('SAP Invoice error');
            mail.setHtmlBody(msg+ '<br/><br/>Errors:<br />'+e);
            mail.setPlainTextBody(msg+ '\n\nErrors:\n\n'+e);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            //log exception in error log
            QUAN_Util.insertErrorLog(e);        
        }
    }

    /**
     * @param invoiceIds
     */
    public static void writeXml(List<String> invoiceIds) {
        
        // RestRequest req = RestContext.request;
        // RestResponse res = RestContext.response;
        String filePrefix = '';
        strategy_Settings_QUAN__c settings = strategy_Settings_QUAN__c.getOrgDefaults();
        if (settings.Id != null && settings.Invoice_File_Prefix_QUAN__c != null) filePrefix = settings.Invoice_File_Prefix_QUAN__c;

        Id recordTypeId = [SELECT Id FROM RecordType WHERE DeveloperName = 'Invoice_QUAN' And SobjectType = 'ContentVersion'].Id;
        Id workspaceId = [SELECT Id FROM ContentWorkspace WHERE Name = 'strategy' Limit 1].Id;

        List<ContentVersion> existingPDFs = [SELECT Id, 
                                                    FirstPublishLocationId, 
                                                    Invoice_QUAN__c 
                                               FROM ContentVersion 
                                              WHERE FileType = 'PDF' 
                                                AND Invoice_QUAN__c IN :invoiceIds];

        Map<ID, ID> invoiceIDToContentWorkspaceIDMap = new Map<ID,ID>();
        for(ContentVersion existingPDF : existingPDFs){
            if(existingPDF.Invoice_QUAN__c != null && existingPDF.FirstPublishLocationId != null){
                invoiceIDToContentWorkspaceIDMap.put(existingPDF.Invoice_QUAN__c, existingPDF.FirstPublishLocationId);
            }
        }

        List<ContentVersion> xmlFiles = new List<ContentVersion>();
        for (String invoiceId : invoiceIds) {
            PageReference xmlFile = Page.QUAN_InvoiceAFIXML;
            xmlFile.getParameters().put('id', invoiceId);
            Blob b = (!Test.isRunningTest()) ? xmlFile.getContent() : Blob.valueOf('<blah></blah>');
            
            ContentVersion invoiceXml = new ContentVersion();
            invoiceXml.Title = filePrefix+invoiceId+'.xml';
            invoiceXml.PathOnClient = filePrefix+invoiceId+'.xml';
            if(invoiceIDToContentWorkspaceIDMap.containsKey(invoiceId)){
                invoiceXml.FirstPublishLocationId = invoiceIDToContentWorkspaceIDMap.get(invoiceId);
            } else {
                invoiceXml.FirstPublishLocationId = workspaceId;                
            }
            invoiceXml.Document_Type_QUAN__c = settings.QUAN_Invoice_XML_Writer_Document_Type__c;
            invoiceXml.RecordTypeId = recordTypeId;
            invoiceXml.Invoice_QUAN__c = invoiceId;
            invoiceXml.VersionData = b; 
            xmlFiles.add(invoiceXml);
        }
        insert xmlFiles;

        //delete any other xml-related documents on this invoice
        Set<Id> contentDocumentIds = new Set<Id>();
        for (ContentVersion cv : [SELECT ContentDocumentId From ContentVersion WHERE Invoice_QUAN__c in :invoiceIds AND Title like '%.xml%' AND Id not in :xmlFiles])
            contentDocumentIds.add(cv.ContentDocumentId);
        try {
            delete [SELECT ID FROM ContentDocument WHERE Id in :contentDocumentIds];
        } catch (Exception e) {
            System.debug('\n\n\nQUAN_InvoiceXmlWriter - '+e.getMessage()+'\n\n\n\n');
            //log exception in error log
            QUAN_Util.insertErrorLog(e);
        }
    }
}

I am getting (85235474)|EXCEPTION_THROWN|[126]|System.CalloutException: Callout loop not allowed from the line marked as bold. Any help is much appriciated.