为什么urlconnection在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,可以使用线程:

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

当应用程序试图在其主线程上执行网络操作时,会引发此异常。

使用AsyncTask运行此任务将帮助您解决此问题。

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

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

}

相关内容

  • 没有找到相关文章

最新更新