Android Studio:获取与URL的连接

时间:2017-10-12 17:44:02

标签: android json android-studio httpwebrequest webrequest

我在项目中加载JSON时遇到了一些麻烦。

我使用了答案中列出的this getJSON方法,但它不起作用。我发现只是connect()函数抛出RuntimeException

这是我的整个课程,包括来自另一个问题的getJSON方法:

private class GetUnis extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(URL2);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            test = sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }
}

我这样称呼它:new GetUnis()。execute();

编辑:这是StackTrace

java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                   at android.os.AsyncTask$3.done(AsyncTask.java:304)
                                                                                   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                                   at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                   at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: java.lang.ClassCastException: com.android.okhttp.internal.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
                                                                                   at com.example.lukaskohl.myapplication.SelectUni$GetUnis.doInBackground(SelectUni.java:138)
                                                                                   at com.example.lukaskohl.myapplication.SelectUni$GetUnis.doInBackground(SelectUni.java:131)
                                                                                   at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                                   at java.lang.Thread.run(Thread.java:818) 

2 个答案:

答案 0 :(得分:1)

你可以从你的线程中调用它,你需要在后台线程中执行此操作

基本上创建一个asynctask并移动你的逻辑连接到那里

使用此代码将json响应作为字符串获取:

/**
     * This method returns the entire result from the HTTP response.
     *
     * @param url The URL to fetch the HTTP response from.
     * @return The contents of the HTTP response.
     * @throws IOException Related to network and stream reading
     */
    public static String getResponseFromHttpUrl(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            InputStream in = urlConnection.getInputStream();

            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\\A");

            boolean hasInput = scanner.hasNext();
            if (hasInput) {
                return scanner.next();
            } else {
                return null;
            }
        } finally {
            urlConnection.disconnect();
        }
    }

这个是检查互联网连接,并将帮助您避免在用户离线时调用此任务

  public static boolean isNetworkAvaliable(Context ctx) {
        ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
       return  ((connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                || (connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState() == NetworkInfo.State.CONNECTED)) ;
    }








    private class GetUnits extends AsyncTask<URL, Void, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(URL... params) {
            URL Url = params[0];

            String searchResults = null;
            try {
                searchResults =getResponseFromHttpUrl(Url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(searchResults!=null){
                try {
                    JSONArray unitsArray = new  JSONArray(searchResults);
                    // do something cool with units
//// TODO: 02/08/2017  
                }catch (Exception e){
                    e.printStackTrace();
                    Log.e("Places","error "+e);
                }

            return searchResults;
        }

        @Override
        protected void onPostExecute(String searchResults) {



        }
    }

答案 1 :(得分:0)

你错误地将它们投射到javax.net.ssl.HttpsURLConnectioncom.android.okhttp.internal.http.HttpURLConnectionImpl

  con = (HttpsURLConnection) u.openConnection();