带URL的Android基本示例

时间:2017-03-06 11:39:40

标签: java android android-studio

我有基本的Android示例,我正在尝试使用以下代码扩展它以获取网站内容:

    try {
        URL u = new URL("http://seznam.cz");
        InputStream is = u.openStream();
        BufferedReader br = new BufferedReader(new
                InputStreamReader(is));
        String s = "";

    } catch (MalformedURLException murle) { murle.printStackTrace();
    } catch (IOException ioe) { ioe.printStackTrace();
    }

所以当前代码是(我的代码在基本示例中有效):

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
        try {
            URL u = new URL("http://seznam.cz");
            InputStream is = u.openStream();
            BufferedReader br = new BufferedReader(new
                    InputStreamReader(is));
            String s = "";

        } catch (MalformedURLException murle) { murle.printStackTrace();
        } catch (IOException ioe) { ioe.printStackTrace();
    }
    }
}

和xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage" />
</LinearLayout>

当我运行它时,我收到以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.lucinka.myfirstapp, PID: 2562
              java.lang.IllegalStateException: Could not execute method for android:onClick
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                  at android.view.View.performClick(View.java:5610)
                  at android.view.View$PerformClick.run(View.java:22265)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: java.lang.reflect.InvocationTargetException
                  at java.lang.reflect.Method.invoke(Native Method)
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                  at android.view.View.performClick(View.java:5610) 
                  at android.view.View$PerformClick.run(View.java:22265) 
                  at android.os.Handler.handleCallback(Handler.java:751) 
                  at android.os.Handler.dispatchMessage(Handler.java:95) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
               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:345)
                  at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
                  at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
                  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 java.net.URL.openStream(URL.java:1057)
                  at com.example.lucinka.myfirstapp.MainActivity.sendMessage(MainActivity.java:37)
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                  at android.view.View.performClick(View.java:5610) 
                  at android.view.View$PerformClick.run(View.java:22265) 
                  at android.os.Handler.handleCallback(Handler.java:751) 
                  at android.os.Handler.dispatchMessage(Handler.java:95) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

这是什么意思?错误在哪里?谢谢你的提示。

2 个答案:

答案 0 :(得分:0)

try {
            URL u = new URL("http://seznam.cz");
            InputStream is = u.openStream();
            BufferedReader br = new BufferedReader(new
                    InputStreamReader(is));
            String s = "";

        } catch (MalformedURLException murle) { murle.printStackTrace();
        } catch (IOException ioe) { ioe.printStackTrace();
    }
  
    

对于上面的代码行,你必须要求异步任务原因android 3.0后android不允许在UI线程上进行任何网络操作,所以你必须调用异步任务

  

答案 1 :(得分:0)

android.os.NetworkOnMainThreadException异常是相关的。您应该使用工作线程来执行网络操作。

Thread t = new Thread(new Runnable() { public void run() { 
  // your code goes here... 
}});
t.start();