【问题标题】:Unable to make a https request from android error - Connection closed by peer无法从 android 错误发出 https 请求 - 连接被对等方关闭
【发布时间】:2020-02-03 23:25:23
【问题描述】:

我正在尝试从 android 到 api 端点“https://api_chamakah.ivilleinc.com/”的 https 请求。但是,无论我尝试什么选项,我都会得到“通过对等方关闭连接”,来自邮递员和浏览器的请求都可以正常工作。

String webUrl = EndPointMethods.BASE_URL  + EndPointMethods.CATEGORIES;
                URL url = new URL(webUrl);
                HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
                try {
                    urlConnection.setSSLSocketFactory(new SSLSocketFactoryExtended());
                } catch (NoSuchAlgorithmException e) {  e.printStackTrace();  }
                catch (KeyManagementException e) { e.printStackTrace();}

                urlConnection.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

【问题讨论】:

    标签: android sslexception


    【解决方案1】:

    使用this tool 后,我认为主机名中的下划线是问题所在。请参阅this thread,它确认了您针对 JDK 的解决方法,并可能解释了其他工具不受影响的原因。

    【讨论】:

    • 谢谢托比,我现在有了更好的理解
    【解决方案2】:

    在进行 Https 调用之前调用此方法解决了问题,但是我仍然不明白实际问题是什么以及该方法如何解决问题,有人可以向我解释一下这个函数针对手头的问题实现了什么

    private void trustEveryone(Context appContext) {
    
            try{
    
                ProviderInstaller.installIfNeeded(appContext);
    
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
    
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }});
    
                SSLContext context = SSLContext.getInstance("TLS");
    
                context.init(null, new X509TrustManager[]{new X509TrustManager(){
    
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }}}, new SecureRandom());
    
                HttpsURLConnection.setDefaultSSLSocketFactory(
                        context.getSocketFactory());
    
            } catch (
                NoSuchAlgorithmException |  GooglePlayServicesNotAvailableException | KeyManagementException |  GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
    
        }
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2013-05-19
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2021-06-02
      相关资源
      最近更新 更多