2013-09-02 2 views
0

Я пытаюсь выполнить следующий код:Не удалось прочитать сервер responseJavaException: javax.xml.xpath.XPathExpressionException: нулевой

function post(url, options) { 
if(options.query) { 
    url += "?"; 
    var delimiter = ""; 
    for(var propName in (options.query||{})) { 
     url += (delemiter + (propName + "=" + escape(options.query[propName]))); 
     delimiter = "&"; 
    } 
} 
document.write("Fetching " + url); 
var code; 

var body = options.body; 
if(body == null) { 
    throw {message:"Body is required"}; 
} 

try { 

    // Open Connection 
    connection = new java.net.URL(url).openConnection(); 

    // Set timeout 
    var timeout = options.timeout != null ? options.timeout : 10000; 
    connection.setReadTimeout(timeout); 
    connection.setConnectTimeout(timeout); 

    // Method == POST 
    connection.setRequestMethod("POST"); 

    // Set Content Type 
    var contentType = "text/xml;charset=utf-8"; 
    connection.setRequestProperty("Content-Type", contentType); 
    connection.setRequestProperty("SOAPAction", "login"); 
    connection.setRequestProperty("User-Agent", "webastra"); 

    // Set Content Length 
    connection.setRequestProperty("Content-Length", body.length); 

    // Silly Java Stuff 
    connection.setUseCaches (false); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 

    //Send Post Data 
    bodyWriter = new java.io.DataOutputStream(connection.getOutputStream()); 
    bodyWriter.writeBytes(body); 
    bodyWriter.flush(); 
    bodyWriter.close(); 

    code = connection.getResponseCode(); 

} 
catch(e) { 
    throw {message:("Socket Exception or Server Timeout: " + e), code:0}; 
} 
if(code < 200 || code > 299) { 
    throw {message:("Received non-2XX response: " + code), code:code}; 
} 
var is = null; 
try { 

    importPackage(java.io, java.net, javax.xml.xpath, org.xml.sax); 
    is = connection.getInputStream(); 
    var str = new String(org.apache.commons.io.IOUtils.toString(is)); 

    var paths = "//serverUrl"; 
    var ips = new InputSource(is); 
    var xPath = XPathFactory.newInstance().newXPath(); 
    ret = xPath.evaluate(paths, ips); 

    document.write(" succ:" + ret); 
    return str; 
} 
catch(e) { 
    document.write("Failed to read server response" + e); 
} 
finally { 
    try {if(is != null)is.close();} catch (err){} 
} 

} 

post("https://abc.com/services/Soap/c/28.0", {body : "<?xml  version=\"1.0\" encoding=\"utf-8\"?> <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:tns=\"urn:enterprise.soap.sforce.com\"> <soap:Header> <tns:LoginScopeHeader> <tns:organizationId/> </tns:LoginScopeHeader> </soap:Header> <soap:Body> <tns:login> <tns:username>[email protected]</tns:username> <tns:password>Thursday12gtz</tns:password> </tns:login> </soap:Body> </soap:Envelope>"}); 

Пост часть прошла успешно. Однако, когда я пытаюсь получить значение XML тега «ServerURL» в переменную RET, я получаю следующее сообщение об ошибке:

Не удалось прочитать сервер responseJavaException: javax.xml.xpath.XPathExpressionException: нулевой

XML, который я получить от должности является:

<?xml version="1.0" encoding="UTF-8"?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
       xmlns="urn:enterprise.soap.sforce.com" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
    <loginResponse> 
     <result> 
      <metadataServerUrl> 
       https://na3.salesforce.com/services/Soap/m/28.0/00D50000000IdrE 
      </metadataServerUrl> 
      <passwordExpired>false</passwordExpired> 
      <sandbox>false</sandbox> 
      <serverUrl> 
       https://na3.salesforce.com/services/Soap/c/28.0/00D50000000IdrE 
      </serverUrl> 
      <sessionId> 
        00D50000000IdrE!AREAQK4VYXRaHoL_uRvOi.QXXw3ahAt2Cge254wygiW7cr_f6DVa2pDC6g57w5IE 
       fidAu3ZRsJFBN5Bwb6DVhF18zKFiVVyT 
      </sessionId> 
      <userId>00550000001Dd4uAAC</userId> 
      <userInfo> 
       <accessibilityMode>false</accessibilityMode> 
       <currencySymbol>$</currencySymbol> 
       <orgAttachmentFileSizeLimit>5242880 
       </orgAttachmentFileSizeLimit> 
       <orgDefaultCurrencyIsoCode>USD</orgDefaultCurrencyIsoCode> 
       <orgDisallowHtmlAttachments>false 
       </orgDisallowHtmlAttachments> 
       <orgHasPersonAccounts>false</orgHasPersonAccounts> 
       <organizationId>00D50000000IdrEEAS</organizationId> 
       <organizationMultiCurrency>false</organizationMultiCurrency> 
       <organizationName>3CLogic</organizationName> 
       <profileId>00e500000017al5AAA</profileId> 
       <roleId xsi:nil="true"/> 
       <sessionSecondsValid>7200</sessionSecondsValid> 
       <userDefaultCurrencyIsoCode xsi:nil="true"/> 
       <userEmail>[email protected]</userEmail> 
       <userFullName>Ramana</userFullName> 
       <userId>00550Dd4uAAC</userId> 
       <userLanguage>en_US</userLanguage> 
       <userLocale>en_US</userLocale> 
       <userName>[email protected]</userName> 
       <userTimeZone>America/New_York</userTimeZone> 
       <userType>Standard</userType> 
       <userUiSkin>Theme3</userUiSkin> 
      </userInfo> 
     </result> 
    </loginResponse> 
</soapenv:Body> 
</soapenv:Envelope> 
+0

Откуда берется 'var'? Это не Ява, верно? –

ответ

0

InputStream уже «пустой» (т.е. чтения), при попытке разобрать его:

is = connection.getInputStream(); 
var str = new String(org.apache.commons.io.IOUtils.toString(is)); // <-- already read 

var paths = "//serverUrl"; 
var ips = new InputSource(is); // <-- now empty 
var xPath = XPathFactory.newInstance().newXPath(); 
ret = xPath.evaluate(paths, ips); 

вы может изменить ваш код соответствующим образом:

var ips = new InputSource(new StringReader(str)); 
Смежные вопросы