2017-10-09 54 views
0

我想從我的應用程序連接到我的Django後端服務器。在http連接的本地/ dev中,android應用程序正在連接到服務器,但通過應用程序進行的所有API調用(登錄調用除外)都會導致HTT 401錯誤。然而,有趣的是使用郵差,我可以到達prod服務器。Android to Django - 總是顯示401

以下是代碼片段之一(機器人):

try{ 
      URL targetUrl = new URL(targetURL); 
      httpConnection = (HttpURLConnection) targetUrl.openConnection(); 
      httpConnection.setRequestMethod("GET"); 
      httpConnection.setRequestProperty("Authorization", "jwt " + mToken); 
      httpConnection.setConnectTimeout(10000); //10secs 
      httpConnection.connect(); 

      Log.i(TAG, "response code:" + httpConnection.getResponseCode()); 
      if (httpConnection.getResponseCode() != 200){ 
       Log.e(TAG, "Failed : HTTP error code : " + httpConnection.getResponseCode()); 
       return Constants.Status.ERR_INVALID; 
      } 

      //Received Response 
      InputStream is = httpConnection.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

      String line; 
      while((line = rd.readLine()) != null) { 
       response.append(line); 
       //response.append('\r'); 
      } 
      rd.close(); 

      Log.i(TAG, response.toString()); 
      // Save the tenant details 
      return parseTenantInfo(response.toString()); 

     }catch (MalformedURLException e) { 
      e.printStackTrace(); 
      return Constants.Status.ERR_NETWORK; 

     } catch (SocketTimeoutException e) { 
      e.printStackTrace(); 
      return Constants.Status.ERR_NETWORK; 
     } 

     catch (IOException e) { 
      e.printStackTrace(); 
      return Constants.Status.ERR_UNKNOWN; 
     }finally { 

      if(httpConnection != null) { 
       httpConnection.disconnect(); 
      } 
     } 

以下是目標URL:

private static final String targetURL = Constants.SERVER_ADDR + APIs.tenant_get; 

這裏,SERVER_ADDR是https://www.example.com/和tenant_get是apitogettenantinfo/

我我總是得到401錯誤。請幫助我!謝謝。

最惱人的是郵差工程,android登錄工程。因此,服務器似乎沒有問題(否則,郵遞員如何工作?)。我無法理解Android的問題。

編輯:

以下是我的郵遞員的截圖。有幾件事情都昏迷了安全&隱私:

http://imageshack.com/a/img923/231/wUrOuS.png

+0

看[https://tools.ietf.org/html/rfc2616#section-10.4.2](https://tools.ietf.org/html/rfc2616#section- 10.4.2)。 – KeLiuyue

+0

'mToken'的價值是什麼?和郵遞員一樣嗎? –

+0

該請求需要用戶驗證。響應必須包含一個WWW-Authenticate頭域(14.47節),其中包含一個適用於所請求資源的挑戰。客戶端可以用適當的授權標題字段重複請求(14.8節)。 – KeLiuyue

回答

0

401指示未經授權的請求,請確保您發送正確的令牌。

而且刪除此httpConnection.connect();

+0

@Sayantan這工作? – Satendra