java - HTTP/1.1 400 对具有基本身份验证的 httpGet 的错误请求

标签 java android authentication certificate

我制作了一个执行 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。为什么? 在我的代码中进行身份验证是否正确?

最佳答案

问题是授权 header 。

我们必须使用:

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”行终止符,如果您在该 header 中使用它是不正确的。

关于java - HTTP/1.1 400 对具有基本身份验证的 httpGet 的错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13524623/

相关文章:

java - JPA ManyToMany 使用分组和交叉连接将数据连接在一起

php - 我们如何通过 Auth::check 在 laravel 4.2 中限制停用的用户

ruby-on-rails - ActiveModel::SecurePassword 未定义方法 `password_digest='

android - Metasploit 创建的 apk 未安装在 Android 设备上

c# - ASP.Net 核心 2 : Default Authentication Scheme ignored

java - ArrayList 与 vector : Which one to use?

java JFrame setContentPanel 然后 JPanel 消失

java - 具有最小冲突的两个整数数组的哈希函数

php - 用手指在移动 Web 应用程序中滑动页面

android - Ffmpeg 命令创建可分享到 Instagram 等的 mp4 视频