Google Apps Script调用Salesforce登录接口报Premature end of file错误
Fixing "Premature end of file" Error in Salesforce SOAP Login via Google Apps Script
Let's break down why you're hitting this error and how to fix it—your Postman request works because it's sending valid XML, but the Google Apps Script (GAS) code has a few formatting issues that are breaking the SOAP request.
Key Issues in Your Code
- Escaped XML Characters: You're using
<and>in your raw XML string, but GAS doesn't need these escapes when defining a multi-line string. Salesforce receives this as literal text instead of valid XML structure, which causes it to throw a parsing error (hence the "Premature end of file" message). - Incorrect SOAPAction Header: The
SOAPActionfor Salesforce's enterprise login should be"urn:enterprise.soap.sforce.com/login"(or simply"login"), not"/". - Unnecessary Cookie: The
BrowserIdcookie from Postman is tied to your Postman session and doesn't belong in a fresh GAS request—removing it avoids potential session conflicts.
Corrected Code
Here's the fixed version of your script:
function salesforceLogin() { // Configure headers with correct SOAPAction const myHeaders = { "Content-Type": "text/xml", "SOAPAction": "urn:enterprise.soap.sforce.com/login" }; // Raw XML with actual angle brackets (no escapes) const raw = ` <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"> <Header> </Header> <Body> <login xmlns="urn:enterprise.soap.sforce.com"> <username>xx@xx.com</username> <password>xx</password> </login> </Body> </Envelope>`; const requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow', muteHttpExceptions: true }; try { const response = UrlFetchApp.fetch("https://test.salesforce.com/services/Soap/c/48.0/", requestOptions); Logger.log(response.getContentText()); } catch (error) { Logger.log('Request failed:', error.toString()); } }
Additional Tips
- Check Password + Security Token: Make sure your password includes the Salesforce security token (unless your IP is whitelisted). If you don't have it, reset it via your Salesforce account settings.
- Validate XML: If you still run into issues, use an XML validator to confirm your raw XML is well-formed before sending it.
- Debug Response: With
muteHttpExceptionsenabled, you can log the full response content to see exactly what Salesforce is returning if there's another issue.
内容的提问来源于stack exchange,提问作者Werner Adewole
相关产品推荐
相关产品推荐

