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

时间:2015-12-03 14:25:12

标签: android httpconnection

我使用此代码获取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;
    }
}

我的问题是什么? 我也加入了互联网许可。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

使用AsyncTask运行此功能将帮助您解决此问题。

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

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

}