2017-10-09 91 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