Con.getInputStream () throw an exception in an Android project, how to fix?

con.getInputStream () throw exception, when the code runs on android, but when copying the code to a regular Java project, it works.
An abandoned e object contains "detailMessage = Permission denied". my code ::

            public static HttpData get(String sUrl) {
                HttpData ret = new HttpData();
                String str;
                StringBuffer buff = new StringBuffer();
                try {
                        URL url = new URL(sUrl);
                        URLConnection con = url.openConnection();
                        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        while ((str = in.readLine()) != null) {
                                buff.append(str);
                        }
                        ret.content = buff.toString();

                        //get headers
                        Map<String, List<String>> headers = con.getHeaderFields();
                        Set<Entry<String, List<String>>> hKeys = headers.entrySet();
                        for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
                                Entry<String, List<String>> m = i.next();

                                Log.w("HEADER_KEY", m.getKey() + "");
                                ret.headers.put(m.getKey(), m.getValue().toString());
                                if (m.getKey().equals("set-cookie"))
                                ret.cookies.put(m.getKey(), m.getValue().toString());
                        }
                } catch (Exception e) {
                        Log.e("HttpRequest", e.toString());
                }
                return ret;
        }

con object while debug

+3
source share
2 answers

adding a tag <uses-permission android:name="android.permission.INTERNET"/>to the manifest will fix the problem. Thanks to James's comment.

+1
source

Make sure you get it <uses-permission android:name="android.permission.INTERNET"/>, not <permission android:name="android.permission.INTERNET"/>! It bit me for an hour ...

+1
source

Source: https://habr.com/ru/post/1788677/


All Articles