首页 > 解决方案 > HttpUrlConnection 在 android 中抛出 IOException

问题描述

我正在尝试让我的应用程序与我的 php 服务器通信,但我在这里感到困惑,这个应用程序在我的 android 手机上运行良好,但是当我将同一个应用程序发送给我的朋友进行审查时,他们无法注册,因为它会引发 IOException。

我知道有很多相关的问题,但没有一个能解决我自己的问题。

     @Override
                protected String doInBackground(Void... voids) {
                    try {
                        URL url = new URL(urlWebService);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setReadTimeout(15000);
                        con.setConnectTimeout(15000);
    
                        try {
                            if(con.getResponseCode() == 200) {
                                StringBuilder sb = new StringBuilder();
                                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                                String json;
                                //con.getInputStream().
    
                                while ((json = bufferedReader.readLine()) != null) {
                                    sb.append(json + "\n");
                                }
    
                                return sb.toString().trim();
                            }
    
                            return "400";
    
                        } catch (IOException e) {
                           //401 is returned once they hit the signup button
  e.printStackTrace();
  Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                            return "401";
                        }
    
                    } catch (Exception e) {
                        return "402";
                    }
                }

当我的朋友尝试注册时,他们得到“401”作为我设置的错误代码

标签: javaandroid

解决方案


我已经解决了这个问题。我发现我朋友的手机从 9 开始运行更高版本的 android 操作系统,而它在我的 8.1.0 上运行良好。由于我通过 http 而不是 https 发出服务器请求,出于安全原因,android 9 pie 不允许这样做。所以我只是通过https而不是http来提出我的请求。


推荐阅读