HttpURLConnection and HEAD/GET methods

I am attempting to validate whether an HTML page exists or not.
I have found that, for about 7% of the pages checked, HEAD and GET methods return different response codes.
I have structured my code such:
1) make initial check using HEAD method
2) for non valid (200) response codes, recheck the page using the GET method.
In this case about 75% of the pages that failed using the HEAD method will work when using the GET method.
So, I guess my questions are:
1) Does anybody know why HEAD/GET return different response codes?
2) Does anybody know a better way to check if a page exists?
Here is the sample program I am using with a few URLs that exhibit this behaviour:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class Internet
     private final static String DEFAULT_LOCAL_HOST = "127.0.0.1";
     private URL url;
     private HttpURLConnection http;
     private int responseCode;
     private String responseMessage;
     public Internet(URL url)
          this.url = url;
     public boolean isValid()
          try
               //  Make first attempt using a HEAD request
               http = (HttpURLConnection)url.openConnection();
               http.setRequestMethod( "HEAD" );
               http.connect();
               System.out.println( "head: " + http.getResponseCode()
               + " : " + http.getResponseMessage() );
               //  GET seems to do a better job, try again
               if ( http.getResponseCode() != HttpURLConnection.HTTP_OK)
                    http = (HttpURLConnection)url.openConnection();
                    http.setRequestMethod( "GET" );
                    http.connect();
                    System.out.println( "get:  " + http.getResponseCode() );
               responseCode = http.getResponseCode();
               responseMessage = http.getResponseMessage();
               if (http.getResponseCode() == HttpURLConnection.HTTP_OK)
                    return true;
               else
                    System.out.println( http.getResponseMessage() );
                    return false;
          catch (IOException e)
               responseCode = -1;
               responseMessage = e.getMessage();
               System.out.println( e );
               return false;
     public static void main(String[] args)
          throws Exception
          URL url = new URL( "http://www.trca.on.ca" );
          Internet internet = new Internet( url );
          System.out.println( internet.isValid() );
          url = new URL( "http://school.discovery.com/sciencefaircentral" );
          internet = new Internet( url );
          System.out.println( internet.isValid() );
          url = new URL( "http://www.amazon.com" );
          internet = new Internet( url );
          System.out.println( internet.isValid() );
}

Using my sample program:
1) about 3K of data is transferred
2) it runs in about 8 seconds
Using InputStream in = http.getInputStream():
1) about 73K of data is transferred
2) it runs in about 15 seconds
Using the getInputStream() method causes the entire file to be transmitted (even though I don't use any read() methods). I don't care about the data.
I want the check to be as fast as possible which is why I use the HEAD method. It doesn't transfer the contents of the file. But why in some cases does it show a response code other than 200?

Similar Messages

  • A question about concurrency and static getter methods

    Hello
    I have a class with some static methods. they just return a reference and doesnt apply any changes.
    something like this:
    public class FieldMapper {
            private static Map<Class,Map<String,String>> fieldMap = new HashMap<Class,Map<String,String>>();
            public static getFields(Class clazz){
                  return fieldMap.get(clazz);
    }my question is, let's consider many users connect to my server and each has its own session, now assume one user want to use FieldMapper.getFields(User.class) and another is going to call FieldMapper.getFields(Employee.class) at same time or a bit milli seconds after, and this method is not synchronized, is there any conflict in calling the method? would this method return wrong reference to the first invocation?
    in genereal, may the concurrency make problem on reading resources? or just on changing resources?
    Thank you very much in advance.

    To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
    Initializing an object reference from a static initializer;
    Storing a reference to it into a volatile field or AtomicReference;
    Storing a reference to it into a final field of a properly constructed object; or
    Storing a reference to it into a field that is properly guarded by a lock. The internal synchronization in thread-safe collections means that placing an object in a thread-safe collection, such as a Vector or synchronizedList, fulfills the last of these requirements. If thread A places object X in a thread-safe collection and thread B subsequently retrieves it, B is guaranteed to see the state of X as A left it, even though the application code that hands X off in this manner has no explicit synchronization.
    Now in the case you have specified you are using HashMap. Which is not designed to be threadsafe as opposed to HashTable or concurrentHashMap. In such a case I would advise against using this. The concurrency problem is caused by race conditions on mutable objects, whether it is reading or writing. If it is mutable, it is susceptible to race conditions. IMHO
    &spades;

  • Form and the get method

    I am using a simple form with one dropdown menu and one
    submit button.
    The form uses the get mothod to send the menu id to another
    page.
    The form must also get another value and send it along with
    the selected menu value.
    The missing value will come from the "prod_id" from my
    recordset, but I do not want to show that value to the user, of
    course, so I do not know how to incorporate it into the form.
    My second page relies on $_GET['prod_id'] and
    $_GET['menu_value']
    The menu_value is in the url, but not the prod_id, as
    explained.
    Thanks for any advice.

    On Fri, 20 Feb 2009 19:19:28 +0000 (UTC), "bregent"
    <[email protected]> wrote:
    > That's what I was going to suggest, with the caveat that
    if this is sensitive
    >information you are trying to hide, it will be visible in
    source view. The fact
    >that you did not want it in the querystring leads my to
    believe this may be the
    >case.
    That's true.
    Gary

  • Get method of HtmlPanelGrid is not getting called

    Hi,
    I'm creating components dynamically.
    I have a dropdown. Based on the selection of dropdown, the corresponding values are displayed and the get method of HtmlPanelGrid should be called.
    First time the panel grid getmethod is getting called. But when i change the value of drop down, panel grid get method is not getting called and its not rendering.
    This is the code:
    JSF:
    Drop Down
    <h:panelGroup>
    <t:selectOneMenu id="selectProjectTypes" onchange="sbmitform();" immediate="true" valueChangeListener="#{ProjectController.projectTypeChanged}" value="#{ProjectController.project.selectProjectTypes}">
    <f:selectItem itemLabel="--------------------" itemValue="-1"/>
    <f:selectItems value="#{ProjectController.projectTypesList}"/>
    </t:selectOneMenu>
    </h:panelGroup>
    Panel Grid
    <h:panelGrid columns="2" rendered="#{ProjectController.projects}" id="test" binding="#{ProjectController.defaultValues}" columnClasses="hunderadfifty" cellpadding="5" />
    Controller:
    public void projectTypeChanged(ValueChangeEvent event) throws AbortProcessingException,Exception {
    String nodeTypeId = null;
    String selectedValue = (String)event.getNewValue();
    getSessionCache().addValue("test", 0, "1");
    if(selectedValue.equalsIgnoreCase(selectedValue)){
    try
    // this.getDefaultValues().setRendered(true);
    // defaultValues=this.getDefaultValues();
    } catch (Exception e)
    e.printStackTrace();
    FacesContext.getCurrentInstance().renderResponse();
    Panel Grid Method
    *public HtmlPanelGrid getDefaultValues() throws Exception {*
    String devlues = (String)getSessionCache().getValue("test");
    Application app = FacesContext.getCurrentInstance().getApplication();
    labelList = nodeTypeFieldsService.getFixedFields(this.getRpUserData(), this.getAuthUser());
    HtmlPanelGrid panelGrid = (HtmlPanelGrid)app.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
    for(int i = 0; i<labelList.size(); i++)
    HtmlOutputText heading = (HtmlOutputText)app.createComponent(HtmlOutputText.COMPONENT_TYPE);
    HtmlPanelGroup panelGroup = (HtmlPanelGroup)app.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
    HtmlInputText inputText = (HtmlInputText)app.createComponent(HtmlInputText.COMPONENT_TYPE);
    String fieldHeading =((ProjectField)labelList.get(i)).getFieldHeading();
    int fieldLength = ((ProjectField)labelList.get(i)).getFieldLength();
    String fieldDescription = ((ProjectField)labelList.get(i)).getFieldDescription();
    String fieldType = ((ProjectField)labelList.get(i)).getFieldType();
    inputText.setValueBinding("value", (ValueBinding) app.createValueBinding("#{ProjectController.newProj}"));
    if(fieldType.equalsIgnoreCase("3"))
    heading.setValue(fieldHeading);
    heading.setTitle(fieldDescription);
    inputText.setMaxlength(fieldLength);
    inputText.setSize(fieldLength);
    UIRDDialog dialog = (UIRDDialog)app.createComponent(UIRDDialog.COMPONENT_TYPE);
    dialog.setTitle("Object Type Dialog");
    dialog.setHeight("370");
    dialog.setWidth("350");
    dialog.setUrl("searchObjectTypeDialog.jsf");
    UIRDIconButton iconButton = (UIRDIconButton)app.createComponent(UIRDIconButton.COMPONENT_TYPE);
    iconButton.setType("button");
    iconButton.setTitle("Search for Object Types");
    iconButton.setIcon("/image/icon/portalicon_search.gif");
    iconButton.setActivateDialog("searchObjectTypeDialog");
    panelGroup.getChildren().add(inputText);
    panelGroup.getChildren().add(iconButton);
    panelGroup.getChildren().add(dialog);
    panelGrid.getChildren().add(panelGroup);
    }else
    panelGroup.getChildren().add(inputText);
    heading.setValue(fieldHeading);
    inputText.setMaxlength(fieldLength);
    inputText.setSize(fieldLength);
    heading.setTitle(fieldDescription);
    panelGrid.getChildren().add(panelGroup);
    panelGrid.getChildren().add(heading);
    panelGrid.getChildren().add(panelGroup);
    HtmlCommandButton createButton = (HtmlCommandButton)app.createComponent(HtmlCommandButton.COMPONENT_TYPE);
    createButton.setId("create");
    createButton.setTitle("Create");
    createButton.setValue("Skapa");
    createButton.setAction(app.createMethodBinding("#{ProjectController.saveProject}", null));
    HtmlCommandButton backButton = (HtmlCommandButton)app.createComponent(HtmlCommandButton.COMPONENT_TYPE);
    backButton.setId("back");
    backButton.setTitle("Cancel");
    backButton.setValue("Avbryt");
    backButton.setAction(app.createMethodBinding("#{ProjectController.cancel}", null));
    panelGrid.getChildren().add(createButton);
    panelGrid.getChildren().add(backButton);
    return panelGrid;
    /* } else {
    return null;
    kindly help me out.
    regards
    venkatraman.P

    Hi,
    I'm having the exact same problem, and it's freaking me out!!! The setGridPanel method is always called but not the getGridPanel. This one is only called the first time the page is rendered, and when I change a drodpdownlist it never gets the gridPanel again! I'm using an HtmlPanelGrid. Anyone can help please?
    Thanks in advance,
    Raquel

  • P and V Getter not called for custom attributes!

    Hi,
    i implemented a new search structure instead of CRMST_QUERY_SLSORD_BTIL for business transaction search.
    I enhanced the new structure with a custom field and generated v and p-getter methods to have a dropdown listbox.
    Unfortunately the p and v getter are not called by the framework.
    The field in the context node is STRUCT./SEW/BILLINGBLOCK.
    I have no idea why this methods are not called by the framework.
    br
    Jürgen

    For the advanced search you do not have to implement a V getter. Instead, you must
    redefine method GET_DQUERY_DEFINITIONS in the implementation class of the view
    controller.

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • Accessing Custom Controller from setter and Getter methods

    Hi Gurus
    How can we access the custom controller from setter and getter methods,is there any way to do that.
    Thanks & Regards
    Rajasekhar

    Hi Steve.
    Thanks very much for valuable information,  the main controller class is getting tracked in mo_owner which is declared as  CL_BSP_WD_VIEW_CONTROLLER, and I'm getting the reference through
    mo_owner ?= owner. (since mo_owner = owner is not getting converted of type mo_owner ). After doing this on whatever the contexnode class (say zl_xxxx_xxx_cnxx) the corressponding context node values are getting turned as  <#ERROR IN METADATA.
    I mean when I'm checking the configuration in bsp_wd_cmpwb configuration tab -> Available Fields->Enlarge the contex node->BTSTATUS (say for Example) there the values are showing as <#ERROR IN METADATA , After executing the above procedure
    I cross checked several times before and after redefining the context node method IF_BSP_MODEL~INIT, before redefining this method UI is working fine, after redefintion UI is throwing below error .
    Exception Details
    CX_SY_REF_IS_INITIAL - Dereferencing of the NULL reference
    Method: CL_BSP_MODEL=>IF_BSP_MODEL_BINDING~IS_ATTRIBUTE_VALID
    Source Text Row: 13
    Thanks & Regards
    Rajasekhar

  • My payment method keeps getting declined and Im getting very irritated now I got a new credit card and it keeps telling me payment method declined ?

    My payment method keeps getting declined and Im getting very irritated now I got a new credit card and it keeps telling me payment method declined ??

    Contact iTune Support
    http://www.apple.com/emea/support/itunes/contact.html

  • Trying to publish an event to fb from iPhoto '09, 8.1.2. Getting error message: "Line 22: Opening and ending tag mismatch: meta line 0 and head".

    Trying to publish an event to fb from iPhoto '09, 8.1.2. Getting error message: "Line 22: Opening and ending tag mismatch: meta line 0 and head". Never had any trouble before. What in the world?

    See if you can export those same photos to a folder on your Desktop.
    OT

  • I purchased gems from a game and didnt get them because my method was declined i want to remove the order so i dont pay for it and so i can update my other apps and i want to remove the method i will be thankfull if someone help me

    i purchased gems from a game and didnt get them because my method was declined i want to remove the order so i dont pay for it and so i can update my other apps and i want to remove the method i will be thankfull if someone help me without updating the payment method i cant update my apps in my iphone i want to remove the method and remove the order i dont want it

    Click here and ask the iTunes Store staff for assistance.
    (125742)

  • Heads and feet getting cropped off in iMovie '09

    My event footage is fine but when I create a project (my video camera is not HD but shoots 16:9) the head and feet get cut off. Suggestions?

    Have you used "analyze for stabilization" at any point? This automatically zooms and crops your clip further to keep the image steady. It discards the edges, possibly decapitating your subjects.

  • Customizing order for setter and getter methods in ViewRowImpl

    I have problem to calculate value for one attribute of my viewObjectRow which depends on values of other attributes in my row and result of stored function. I menaged to do all of this except getting value one of attributes that i need. Order of calling getter methods doesn't fit me. I tried lot of things, but nothig worked! Is there some way to customize calling order for getter and setter methods in ViewRowImpl and How?
    Thanks!

    but why addign javadoc to a getter/setter anywhy?Oracle [url http://download.oracle.com/docs/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/common/AccTravDefImpl.html#getAccTravQualifiers()]does, so it must be OK :)
    But as Timo says, there's no automatic way that I know of. I suppose you could do something like that by making your own code template.
    John

  • Hey guys, i get the message "Your Apple ID was deaktivated" I have changed my password and the pay method too but nothing happens

    Hey guys, i get the message "Your Apple ID was deaktivated" I have changed my password and the pay method too but nothing happens

    After resetting your password have you tried logging out of your account on your phone by tapping on your id in Settings > iTunes & App Store and then logging back in to see if that 'refreshes' the account on it and if it then works ?
    If that doesn't fix it then you might need to contact iTunes Support : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page

  • Doubts in CMP Setter and Getter Methods

    Hi. Just like to clarify something on CMP.
    May I know if there are 6 fields in my database table and I declared only getter and setter methods for 5 of the fields only, will this post any problem in WL8.1?
    Also, suppose I have 6 fields in my database table and I declared 6 setter and getter methods. Throughout my program I only trigger 2 setter methods, will the other 4 setter methods that I didnt trigger set a null or 0 to the fields (since I didn't set any value to them)?
    Thanks and appreciate.

    Unset fields will usually be set to their default value, i.e. null for Objects. You don't have to define / execute setters for columns in the database unless they are non-nullable.
    -- markus.

  • Regarding setter and getter methods

    Hi,
    Can anybody tell me the use of setter and getter methods in webdynpro .
    It is generated when we set the calculate property of value attribute to true .
    Thanks a lot .

    Hi Jain
    <b>setter</b> and <b>getter </b>functions will be created when you set the calculated propertyto true
    Consider the following scenario where in you can get some basic idea
    1) First insert a Child "Image" UI Element
    2) Create a Context in a view in which you are using Image UI Element
    3) Value Node
    Name : Image
    Cardidality : 1..1
    4) create 2 Value Attributes
    4)a ImageAlt (Calculate property - true) //this will create getter and setter methods
    4)b ImageSrc (Calculate property - true) //this will create getter and setter methods
    5)Bind the properties of Image
    alt - Image.ImageAlt
    source - Image.ImageSrc
    6) in getImageSrc()
    retrun "XX.gif"
    7) in getImageAlt()
    return "Image Not Available"
    you can even achieve getter and setter methods by doing the following procedure
    goto <b>implementation</b> tab-> rightclick -> <b>source</b> -> <b>generate Getter and Setter methods...</b>
    Best Regards
    Chaitanya.A

Maybe you are looking for

  • Using a FLV file in Flash for Web Graphic

    Hello thank you for looking in. I made a FLV file in After effects. 5 seconds long. I would like to convert it (So I think) in Flash so I can park it on my website for some 'eye candy' I was able to import the FLV an After Effects creation exported a

  • How to get a long text into the SapScript

    Hi. I need to read text from header field from ME21N. I use to this READ_TEXT function module, which is called from SapScript but the problem is, that this function returns me just about 80 chars and trim rest of string. First idea was use loop in fo

  • How to Edit the subject of a form that is submitted to me via email?

    Is there a way to Edit the subject of a form that is submitted to me via email? Ex. I've created multiple forms in Dreamweaver. They are submitted to my email address without problem. When I receive them, the default subject line in my email is "Form

  • Can't connect to os 10.4 server from windows

    i'm trying to connect fromwindows to my OS X 10.4 server and i am running into a variety of problems. at this point i DO get a login window but i never am able to connect. any ideas? it seems to be a domain issue, but i am not doing DNS... here's the

  • Scanner software stops on page 2

        I am trying to use HP Solutions Center to scan a multi-page B&W text document to a PDF file. Each time I try it aborts about 1/3 of the way into feeding page 2 through the document feeder. Error message is "An error occurred in the scanning softw