HttpGet в андроиде .. что я делаю не так? - PullRequest
0 голосов
/ 05 декабря 2011

У меня есть этот код из книги, которую я должен узнать об Android .. что не так?
Я всегда получаю 01 Error Connecting, что является исключением из моего кода при установлении http-соединения.

public class HttpImgActivity extends Activity {

    private InputStream OpenHttpConnection(String urlString)
    throws IOException
    {
        InputStream in = null; // creating My input
        int response = -1;
        URL url= new URL(urlString);
        URLConnection conn = url.openConnection();

        if(!(conn instanceof HttpURLConnection)) // if not a valid URL
            throw new IOException ("NOT an Http connection");

        try{
            HttpURLConnection httpconn = (HttpURLConnection) conn;
            httpconn.setAllowUserInteraction(false); // prevent user interaction
            httpconn.setInstanceFollowRedirects(true);
            httpconn.setRequestMethod("GET");
            httpconn.connect(); //initiates the connection after setting the connection properties
            response = httpconn.getResponseCode(); // getting the server response

            if(response == HttpURLConnection.HTTP_OK ) // if the server response is OK then we start receiving input stream
                {   in = httpconn.getInputStream(); }
            } // end of try
        catch(Exception ex)
        {
            throw new IOException(" 01 Error Connecting");          
        }
        return in; // would be null if there is a connection error

    } // end of my OpenHttpConnection user defined method

    */

    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap= null;
        InputStream in = null;
        try
        {
            in = getInputStreamFromUrl(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch (IOException e1)
        {
            Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }

        return bitmap; // this method returns the bitmap which is actually the image itself
    }

    ImageView img;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bitmap bitmap = DownloadImage("http://www.egyphone.com/wp-content/uploads/2011/05/Samsung_Galaxy_S_II_2.jpg");
        img =(ImageView) findViewById(R.id.myImg);
        img.setImageBitmap(bitmap);
    }
}

Есть идеи?

1 Ответ

1 голос
/ 05 декабря 2011

Кажется, вы поймали свое исключение, но вы его ни для чего не используете.

Попробуйте изменить
throw new IOException(" 01 Error Connecting");
на
throw new IOException(ex.toString());

И вам следует подумать об использовании инструментов журналирования Android вместо того, чтобы видеть ошибки через logcat:

...
catch(Exception ex)
{
  Log.e("CONNECTION", ex.toString(), ex);
}
...

Это облегчает отладку IMO.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...