2016-03-15 57 views
0

我的目標是從API獲取xml。我使用的API URI包括參數是http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven。我有一個用戶名和密碼,我認爲這可能是基本授權。Android:沒有通過http獲取xml獲取基本認證請求

我嘗試了各種東西,如Authenticator,格式http://username:[email protected]/ns-api-treinplanner,但在很多SO搜索結束時,我最終得到了帶有基本授權的setRequestProperty

我把代碼放到了一個AsyncTask中,這似乎能正常工作,所以我只是把doInBackground的代碼放在這裏。

作爲java FileNotFoundException我第一次沒有給我太多的信息,我發現如何使用getErrorStream瞭解更多。

  InputStream in; 
      int resCode; 

      try { 
       URL url = new URL("http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven"); 

       String userCredentials = "username:password"; 
       String encoding = new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT)); 

       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
       urlConnection.setRequestProperty("Authorization", "Basic " + encoding); 
       urlConnection.setRequestMethod("GET"); 
       urlConnection.setDoOutput(true); 

       try { 
        resCode = urlConnection.getResponseCode(); 
        if (resCode == HttpURLConnection.HTTP_OK) { 
         Log.i("rescode","ok"); 
         in = urlConnection.getInputStream(); 
        } else { 
         Log.i("rescode","not ok"); 
         in = urlConnection.getErrorStream(); 
        } 
        BufferedReader bufferedReader = new BufferedReader(
          new InputStreamReader(in)); 
        StringBuilder stringBuilder = new StringBuilder(); 
        String line; 
        while ((line = bufferedReader.readLine()) != null) { 
         stringBuilder.append(line).append("\n"); 
        } 
        bufferedReader.close(); 
        return stringBuilder.toString(); 
       } 
       finally{ 
        urlConnection.disconnect(); 
       } 
      } 
      catch(Exception e) { 
       Log.e("ERROR", e.getMessage(), e); 
       return null; 
      } 

然後,在onPostExecute我打印的反應,但我得到的迴應是

<?xml version="1.0"?> 
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding"> 
<soap:Header></soap:Header> 
<soap:Body><soap:Fault> 
<faultcode>soap:Server</faultcode> 
<faultstring>006:No customer found for the specified username and password</faultstring></soap:Fault> 
</soap:Body></soap:Envelope> 

這當然是不對的,它應該給一個完整的XML在這種情況下,一列火車航程推薦。

我用我的瀏覽器進行了測試,並且使用了一個名爲Postman的HTTP請求工具,它返回了正確的xml,所以所有的URI,參數,用戶名和密碼都是正確的。

回答

1

使用的編碼是錯誤的。使用的base64編碼隨機地在中間返回空格,添加encoding = encoding.replaceAll("\\s+","");實際上修復了它。