java - 将 url 加载到字符串变量

标签 java android string url

我需要从 url 加载文本文件并将加载的数据写入字符串变量。我尝试了很多例子,但我没有任何想法来解决这个简单的问题。我使用最小 SDK 9 和目标 SDK 版本 23。在明星应用程序上的这段代码中,我有信息“抱歉,但您的应用程序已停止”。

    public String GetVersionApk(String addres) {
    URL url;
    InputStream is = null;
    DataInputStream dis;
    int line;
    StringBuilder x = new StringBuilder();
    byte[] bytes = new byte[1000];

    try {
        url = new URL(addres);
        is = url.openStream();  // throws an IOException
        dis = new DataInputStream(new BufferedInputStream(is));

        while ((line = dis.read(bytes)) >= 0) {
            x.append(new String(bytes, 0, line));
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException ioe) {
        }
    }
    return x.toString();
}

登录猫:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.piotr.gm/com.example.piotr.gm.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2370) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2432) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference at com.example.piotr.gm.MapsActivity.GetVersionApk(MapsActivity.java:67) at com.example.piotr.gm.MapsActivity.onCreate(MapsActivity.java:83) at android.app.Activity.performCreate(Activity.java:6865) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2323)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2432)             at android.app.ActivityThread.access$900(ActivityThread.java:154)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:135)             at android.app.ActivityThread.main(ActivityThread.java:5310)             at java.lang.reflect.Method.invoke(Native Method)             at java.lang.reflect.Method.invoke(Method.java:372)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

编辑[2015年10月22日]: 我更新了我的函数,因为我发现该函数必须在 AsyncTask 中运行

private class GetVersionApk extends AsyncTask<String,String,String> {
    public AsyncResponse delegate = null;
    protected String doInBackground(String... urls) {
        URL url;
        InputStream is = null;
        DataInputStream dis;
        int line;
        StringBuilder x = new StringBuilder();
        byte[] bytes = new byte[1000];

        try {
            url = new URL(urls[0]);
            is = url.openStream();  // throws an IOException
            dis = new DataInputStream(new BufferedInputStream(is));

            while ((line = dis.read(bytes)) >= 0) {
                x.append(new String(bytes, 0, line));
            }
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try{
                    is.close();
            } catch (IOException ioe) {
            }
        }
        return x.toString();
    }
}

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        Log.i("Version APK SERVER", String.valueOf(new GetVersionApk().execute("http://url.example.com/update.php")));

        //setUpMapIfNeeded();
    }

在控制台日志中我建议:

Version APK SERVER﹕ com.example.piotr.gm.MapsActivity$GetVersionApk@24ed514e

在服务器文件返回文本:1akkkk

我知道,我必须在这个函数中返回结果,但是如何返回?

protected void onPostExecute(String result) {
            delegate.processFinish(result);
        }

最佳答案

您应该执行以下操作,并且仅在 InputStream 不为 null 时才尝试关闭它。

try {
    if(is != null) {
        is.close();
    }
} catch (IOException ioe) {
}

关于java - 将 url 加载到字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270159/

相关文章:

java - Gmail抽屉导航效果

javascript - 检查字符串是否包含与正则表达式匹配的子字符串

android - 如何使用 ADB 将文件复制到多个设备?

java - PolyUtil 解码 JavaScript 和 Java 的区别

string - Swift - 查找字符串中两个位置之间的子字符串

c++ - 用 const char* 填充 wstring 的最佳方法

java - 测试重写的 equals 方法

java - L10N : why was the default language applied

Java索引越界异常索引:2,大小:2

java - RenderedImage 到 BufferedImage 用于多页 tiff 读取