为什么 urlconnection 在 android 中不起作用?

Why urlconnection not work in android?

我使用此代码获取 www.p30download.com 的内容,但什么也没得到。

代码:

package com.mycompany.htp;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.net.*;

public class MainActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        Integer result = 0;
        try {
            /* forming th java.net.URL object */
            URL url = new URL("http://www.p30download.com/");
            urlConnection = (HttpURLConnection) url.openConnection();

            /* optional request header */
            urlConnection.setRequestProperty("Content-Type", "application/json");

            /* optional request header */
            urlConnection.setRequestProperty("Accept", "application/json");

            /* for Get request */
            urlConnection.setRequestMethod("GET");
            int statusCode = urlConnection.getResponseCode();

            /* 200 represents HTTP OK */
            if (statusCode ==  200) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                String response = convertInputStreamToString(inputStream);
                Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
                result = 1; // Successful
            }else{
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
        }
    }
    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null){
            result += line;
        }

        /* Close Stream */
        if(null!=inputStream){
            inputStream.close();
        }
        return result;
    }
}

我的问题是什么? 我也添加了互联网权限。

当应用程序试图在其主线程上执行网络操作时抛出此异常。

运行 这个加上AsyncTask 会帮你解决的。

或者你可以使用这个(不推荐)

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

}

如果不想使用AsyncTask,可以使用线程:

Thread thread=new Thread(new Runnable(){
    public void run(){
        //you put your network code here
    }
}).start();