2011-12-04 31 views
0

我有一本书中的代码,我必须了解Android。有什么不对?
我总是得到01 Error Connecting这是我的代码中的异常,同时建立http连接。Android中的HttpGet ..我做错了什么?

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

任何想法?

+0

你确定你把权限放在清单中吗? –

+1

那么,你会得到一个'IOException'。请开始为自己调试。从异常消息开始(可能是'ex-> getMessage()')。然后检查如何修复引发异常的代码。 – Nanne

+0

他为什么会陷入低谷?这似乎是SO所要回答的问题。 – user94154

回答

1

看来你发现了你的例外,但你不用它来做任何事情。

尝试改变
throw new IOException(" 01 Error Connecting");

throw new IOException(ex.toString());

你应该考虑使用Android的记录工具,而不是通过logcat的看到你的错误:

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

这使得IMO调试更加方便。