Android中的HttpGet ..我做错了什么?

时间:2011-12-04 21:25:14

标签: android get

我有一本书中的代码,我必须学习Android ..出了什么问题? 在建立http连接时,我总是得到01 Error Connecting这是我的代码中的一个例外。

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 个答案:

答案 0 :(得分:1)

你似乎抓住了你的异常,但你不会将它用于任何事情。

尝试将throw new IOException(" 01 Error Connecting");
更改为throw new IOException(ex.toString());

你应该考虑使用Android的日志工具,而不是通过logcat查看错误:

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

这使调试更容易IMO。