为什么我的代码没有连接到给定的 url

why my code does not get connected with the given url

public class MainActivity extends Activity {

String  myUrl="http://www.google.com.bd/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String result;
    try {
        result = doHttpUrlConnectionAction(myUrl);
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "in exception", Toast.LENGTH_LONG).show();
    }


}


private String doHttpUrlConnectionAction(String desiredUrl) throws Exception {
    // TODO Auto-generated method stub
    URL url=null;
    String result;
    try {
        url=new URL(desiredUrl);
        HttpURLConnection connection=(HttpURLConnection)    url.openConnection();
        connection.setRequestMethod("GET");

        connection.setReadTimeout(15*1000);
        connection.connect();
        result="connected";

    } catch (Exception e) {
        // TODO: handle exception
        result="disconnected";
    }
    return result;
}

}

我认为此代码将与给定的 url 连接,但此代码始终显示断开连接 message.I 使用 ACCESS_NETWORKS_STATEAndroidManifest.xml 中的 INTERNET 权限。请帮我。我想在我的大学项目中使用此代码。

这个问题问了多个没有。以前也

但将此添加到您的 androidmanifest.xml

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

并使用 AsyncTask() class 进行网络操作。如果你想在主线程上进行操作,请在操作前使用这行代码

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

使用异步任务与 http 连接交互。