0

I use this code to get content of www.p30download.com but get nothing.

Code:

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;
    }
}

What is my problem? I added internet permission too.

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
Mohsen
  • 309
  • 3
  • 15

2 Answers2

2

If you don't want to use AsyncTask, you can use a thread:

Thread thread=new Thread(new Runnable(){
    public void run(){
        //you put your network code here
    }
}).start();
Fustigador
  • 6,339
  • 12
  • 59
  • 115
1

This exception is thrown when an application attempts to perform a networking operation on its main thread.

Run this with AsyncTask will help you resolve it.

Or you can use this (Not recommend)

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

}

Tran Vinh Quang
  • 585
  • 2
  • 9
  • 30