通过Android进行Http身份验证

时间:2014-10-25 18:22:28

标签: android http authentication httpclient http-status-code-401

我目前尝试在Android上进行身份验证,就像我使用Postman here进行身份验证一样。

我在互联网上随处可见一些例子,我想出了这段代码:

 protected String doInBackground(Void... voids) {
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);

        try{
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("_username", mylogin));
            nameValuePairs.add(new BasicNameValuePair("_password", mypassword));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = client.execute(httppost);
            StatusLine status = response.getStatusLine();

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception("Status Error CODE : " + status.getStatusCode());
            }

            HttpEntity entity = response.getEntity();
            InputStream in = entity.getContent();
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            int readCount;
            while ((readCount = in.read(buff)) != -1)
            {
                out.write(buff, 0, readCount);
            }
            return new String (out.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

我一直收到错误401,我不明白为什么。有什么我没看到的吗?

顺便说一下,我也尝试使用它的method,但没有变好。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

找到解决方案,问题不是来自Android,而是来自Symphony下的服务器。 Symphony需要在接受请求之前创建会话。