【问题标题】:HTTP/1.1 400 Bad Request on httpGet with Base Authentication使用基本身份验证的 httpGet 上的 HTTP/1.1 400 错误请求
【发布时间】:2012-11-11 13:19:45
【问题描述】:

我制作了一个执行 httpGet 的应用程序。

我的应用程序使用我自己的证书,因此服务器需要用户登录。 对于证书,我使用了this 教程。

对于 httpGet 我已经做了这个实现:

 HttpClient client = new CustClient(getApplicationContext()); // HttpClient that uses my certificates



               // Example send http request
               final String url = "https://ip:port/";// <--in  my implementation i've a right url
               HttpResponse response = null;

               HttpGet httpGet = new HttpGet(url);

               //login
               httpGet.addHeader("Authorization", "Basic "+Base64.encodeToString("root:root".getBytes(),Base64.DEFAULT));

               StringBuilder testo = null;
               try {
                response = client.execute(httpGet);
                InputStream contenuto = response.getEntity().getContent();
                BufferedReader rd = new BufferedReader(new InputStreamReader(contenuto));

                String line;
                // Read response until the end
                while ((line = rd.readLine()) != null) { 

                    testo.append(line); 
                }
            } catch (Exception e) {

            } 

为什么我做出 client.execute(httpGet) 响应是 HTTP/1.1 400 Bad Request。为什么? 在我的代码中进行身份验证是否正确?

【问题讨论】:

  • 看起来不错 :) 我的第一个问题是为什么不使用:hc.apache.org/httpclient-3.x/authentication.html?至于你的问题,我会先尝试通过常规 http 并尝试使用wireshark 或其他东西拦截请求,并查看服务器错误日志以获取线索。
  • 欢迎您的评论!但是我没有使用 client.getParams() 因为在 Android HttpClient 中没有这种方法(我认为也没有类似的方法)。 Fiddler帮我解决这个问题!

标签: java android authentication login certificate


【解决方案1】:

问题在于授权标头。

我们必须使用:

httpGet.addHeader("Authorization", "Basic "+Base64.encodeToString("root:root".getBytes(),Base64.NO_WRAP));

代替:

httpGet.addHeader("Authorization", "Basic "+Base64.encodeToString("root:root".getBytes(),Base64.DEFAULT));

因为 DEFAULT 参数在字符串末尾添加了“CR”行终止符,如果您使用该标题是不正确的。

【讨论】:

  • 你刚刚拯救了我的一天:')
  • 还有我的。谢谢!
  • 很棒的答案,这在没有 Google 帮助的情况下挽救了我的一天。谁能解释一下为什么两者不同?
猜你喜欢
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2017-07-23
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
相关资源
最近更新 更多