Thursday, 25 August 2011

HttpGet Conncetion in andorid

public static InputStream openHttpConnectionn(String urlStr) {

        InputStream in = null;

        int resCode = -1;

        try {
        if(Constants.LOG)Log.d("openHttpConnection", "URL:"+urlStr);
        URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();//Opening Connection
                    
        if (!(urlConn instanceof HttpURLConnection)) {

                      throw new IOException ("URL is not an Http URL");
        }
        if(Constants.LOG)Log.d("openHttpConnection", "httpConn:1");

        HttpURLConnection httpConn = (HttpURLConnection)urlConn;

        httpConn.setAllowUserInteraction(false);

        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux "+"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
        httpConn.setRequestProperty("Content-Type", "image/*");
//        HttpConnectionParams.setConnectionTimeout((HttpParams) httpConn, Constants.CONNECTIONTIMEOUT);
//        HttpConnectionParams.setSoTimeout((HttpParams) httpConn, Constants.CONNECTIONTIMEOUT);
        httpConn.setConnectTimeout(Constants.CONNECTIONTIMEOUT);
        httpConn.setReadTimeout(Constants.CONNECTIONTIMEOUT);
       
        if(Constants.LOG)Log.d("openHttpConnection", "setting requests and properties");
       
        httpConn.connect();
       
        if(Constants.LOG)Log.d("openHttpConnection", "Connected successfully");
       
        resCode = httpConn.getResponseCode();  
       
        if(Constants.LOG)Log.d("openHttpConnection", "resCode"+resCode);
       
        if (resCode == HttpURLConnection.HTTP_OK) {
       
        in = httpConn.getInputStream();
       
        if(Constants.LOG)Log.d("openHttpConnection", "Fetchinf data done");
       
        }       

        } catch (MalformedURLException e) {

                      e.printStackTrace();

                      if(Constants.LOG)Log.d("openHttpConnection", "1"+e);

        } catch (IOException e) {

                      e.printStackTrace();

                      if(Constants.LOG)Log.d("openHttpConnection", ""+e);

        }catch (Exception e) {
            // TODO: handle exception
            return null;
        }

        return in;
}

No comments:

Post a Comment