3

I am using following code and it keeps giving me malformedurlexception error. The funny part is I have copied it from another project which the same code is working properly. I was wondering if anyone can see what the problem might be. The section of code which is giving the error is in OpenHttpConnection function and at start where it says:

URL url = new URL(urlString); 
URLConnection conn = url.openConnection();

I appreciate any help I can get.

Bitmap bitmapOrg = null;
bitmapOrg = DownloadImage("http://www.bagherpour.com/apache_pb.gif");

public Bitmap DownloadImage(String txt)
{    

    Bitmap bitmap = null;
    InputStream in = null;   
    try {           
        in = OpenHttpConnection(txt);
        bitmap = BitmapFactory.decodeStream(in);

        in.close();
        return bitmap;     
    } catch (IOException e1) {
        e1.printStackTrace();
        Log.d("bitMap",e1.toString());
        return null;
    }                
}

public InputStream OpenHttpConnection(String urlString) 
    throws IOException
        {
            InputStream in = null;
            int response = -1;

            URL url = new URL(urlString); 
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))                     
                throw new IOException("Not an HTTP connection");

            try{
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect(); 

                response = httpConn.getResponseCode();                 
                if (response == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();                                 
                }                     
            }
            catch (Exception ex)
            {
                throw new IOException("Error connecting");            
            }
            return in;     
Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
Farshid
  • 41
  • 2
  • 6
  • 2
    You got the URL wrong. Clearly it doesn't start with http:// at all. – user207421 Sep 11 '12 at 01:04
  • But I have hard code the http:// into the urlString. How can get it right? – Farshid Sep 11 '12 at 05:46
  • What line are you getting the MalformedURLException on? – Jon Lin Sep 11 '12 at 16:25
  • I changed the code to URL url = new URL("http","www.bagherpour.com","/apache_pb.gif"); then MalformedURLException was gone but I still can not connect. It says W/System.err(968): java.io.IOException: Error connecting. This happens when I do httpConn.connect(); – Farshid Sep 11 '12 at 18:09

1 Answers1

-5

Change to:

URL rul = new URL("httpwww.bagherpour.com/apache_pb.gif")
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453