在使用InputStreamReader进行URL读取时出现异常。

huangapple go评论88阅读模式
英文:

Exception in using InputStreamReader for URL reading

问题

以下是您提供的内容的翻译部分:

public String GetString() {
    String URL_API = "https://api.openweathermap.org/data/2.5/onecall?lat=52.249137&lon=104.362658&exclude=minutely,daily&appid=8eac3b7a97a56cb537f453eb7a*****";
    String s = "开发异常";
    try {
        URL url = new URL(URL_API);
        URLConnection con = url.openConnection();
        InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
        BufferedReader sc = new BufferedReader(inputStreamReader);
        while ((s = sc.readLine()) != null) {
            s += s + sc.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return s;
}
2020-08-23 18:19:29.549 19308-19308/com.example.teststart1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.teststart1, PID: 19308
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.teststart1/com.example.teststart1.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
        ...
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

请注意,这只是您提供内容的翻译部分,我已经排除了代码以外的所有其他内容。如果您有任何问题或需要进一步的帮助,请随时问我。

英文:

gues! I am doing a program to get weather from json(weathermapApi). I did function for get all text from resource, but Android Studio don't compile my project. Exception on
InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
help me, PLEASE!

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: java -->

 public String GetString() {
        String URL_API= &quot;https://api.openweathermap.org/data/2.5/onecall?lat=52.249137&amp;lon=104.362658&amp;exclude=minutely,daily&amp;appid=8eac3b7a97a56cb537f453eb7a*****&quot;;
        String s = &quot;Exception of develop&quot;;
        try {
            URL url = new URL(URL_API);
            URLConnection con = url.openConnection();
            InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
            BufferedReader sc = new BufferedReader(inputStreamReader);
            while ((s=sc.readLine())!=null) {
              s += s + sc.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return s;

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

2020-08-23 18:19:29.549 19308-19308/com.example.teststart1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.teststart1, PID: 19308
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.teststart1/com.example.teststart1.MainActivity}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6238)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
        at java.net.InetAddress.getAllByName(InetAddress.java:752)
        at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
        at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:346)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:247)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
        at com.example.teststart1.MainActivity.GetString(MainActivity.java:42)
        at com.example.teststart1.MainActivity.onCreate(MainActivity.java:33)
        at android.app.Activity.performCreate(Activity.java:6857)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)&#160;
        at android.app.ActivityThread.-wrap12(ActivityThread.java)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:102)&#160;
        at android.os.Looper.loop(Looper.java:163)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:6238)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)&#160;

<!-- end snippet -->

答案1

得分: 0

android.os.NetworkOnMainThreadException

这个异常是在应用程序试图在其主线程上执行网络操作时抛出的。

你应该使用线程,例如:

Thread thread = new Thread(new Runnable() {
    
    @Override
    public void run() {
        try  {
            //在这里添加你的代码
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start();

确保在 Android 的 manifest.xml 文件中添加了这个权限:

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

有几种方法可以避免 android.os.NetworkOnMainThreadException,例如:

  1. 异步任务(Async Task)(已被弃用)
  2. 意图服务和广播接收器(Intent service and broadcast receiver)

你可以使用像以下这样的库:

  1. Volley
  2. Retrofit
  3. OKHTTP

如果你在谷歌上搜索,你可以找到很多在后台调用 API 并在主线程中提供回调的选项或库。

英文:

android.os.NetworkOnMainThreadException

This exception is thrown when an application attempts to perform a networking operation on its main thread.

You should use threads like

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start();

Check that you have added this permission in android manifest.xml file:

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;

There are several solutions to avoid android.os.NetworkOnMainThreadException like

  1. Async Task (Which is deprecated)
  2. Intent service and broadcast reciever

You can Use libraries like:

  1. Volley
  2. retrofit
  3. OKHTTP

If you google it you can find plenty of option or libraries to call API in background and provide call back in Main thread.

huangapple
  • 本文由 发表于 2020年8月23日 18:32:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63545921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定