如何从Android Java中的网页获取信息

如何从Android Java中的网页获取信息,第1张

概述香港专业教育学院一直试图从网页获取信息成字符串到我的Android应用程序.我一直在使用这种方法.importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjav

香港专业教育学院一直试图从网页上获取信息成字符串到我的Android应用程序.我一直在使用这种方法.

import java.io.BufferedinputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.inputStream;import java.io.inputStreamReader;import java.net.httpURLConnection;import java.net.URL;import java.net.URLConnection;public class DownloadPage {    private static int arraySize;    public static int getArraySize() throws IOException {        URL url = new URL("http://woah.x10host.com/randomfact2.PHP");        httpURLConnection urlConnection = (httpURLConnection) url.openConnection();        inputStream in = new BufferedinputStream(urlConnection.getinputStream());        BufferedReader br = new BufferedReader(new inputStreamReader(in, "UTF-8"));        String size = br.readline();        arraySize = Integer.parseInt(size);        return arraySize;    }}

我什至在我的AndroIDManifest.xml文件中包含了权限

<uses-permission androID:name="androID.permission.INTERNET" /><uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE"/>

但是,我一直收到错误,我的应用程序无法启动.每当我调用方法或类时,它就会崩溃.

解决方法:

您似乎正在获取androID.os.networkonmainthreadException.
请尝试使用AsyncTask来获取该整数.

public class DownloadPage {    private static int arraySize;    public voID getArraySize() throws IOException {        new RetrIEveInt().execute();    }    private class RetrIEveInt extends AsyncTask<String, VoID, Integer> {        @OverrIDe        protected Integer doInBackground(String ... params) {            try {                URL url = new URL("http://woah.x10host.com/randomfact2.PHP");                httpURLConnection urlConnection = (httpURLConnection) url.openConnection();                inputStream in = new BufferedinputStream(urlConnection.getinputStream());                BufferedReader br = new BufferedReader(new inputStreamReader(in, "UTF-8"));                String size = br.readline();                arraySize = Integer.parseInt(size);            } catch (Exception e) {                //do something            }            return arraySize; // gets 18        }        protected voID onPostExecute(Integer i) {            // Todo: do something with the number// You would get value of i == 18 here. This methods gets called after your doInBackground() with output.            System.out.println(i);         }    }}
总结

以上是内存溢出为你收集整理的如何从Android Java中的网页获取信息全部内容,希望文章能够帮你解决如何从Android Java中的网页获取信息所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1079692.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存