Call a website page URL within Java code
I need to call a remote website from my code and get the html data onto a string variable.
How do I do this using Java ?
I need to call a remote website from my code and get the html data onto a string variable.
How do I do this using Java ?
Brandon, would you mind elaborating your requirement further ?
Details such as the Java version you are using, platform you are developing for (Desktop or Web), would help us in guiding you to the solution.
This is because solution depends on the context of the problem. In Java you need to be more specific.
I am currently using JDK 6.0. I am implementing a e-commerce web application using Java and JSF.
The application server is Glassfish. My development environment is Netbeans.
The requirement is that I have to call an external page by passing some parameters. The destination page returns the values inform of an XML string. I need to process the results and update a database.
Thank you for the information. It is possible to call an external page internally from Java code.
You create a IO Stream to the destination URL and then read the values to a string buffer.
It is similar to opening a file, the difference is that you give the URL as the path.
Would it be possible to show me some sample code?
I tried the File object and passed the URL as a parameter. Â It did not work. Â Maybe I am importing the wrong libraries?
Â
When you need to access a remote page , you actually need to use the "URL" object.
The following code will help you:
StringBuilder dataBuffer = new StringBuilder();Â Â Â
try {
      BufferedReader in = new BufferedReader(new InputStreamReader(new URL(sPath).openStream()));
      String line ="";
      while ((line = in.readLine()) != null) {
        dataBuffer.append(line);
        line = "";
      }  Â
      in.close();
    }
      catch (Exception e) {
         log.error(e.getMessage(),e);
   }
DimaZ beat me to posting the code 🙂
DimaZ's code is correct. What he is doing is that reading the web request chunk by chunk. This is because the Web server streams the file line by line. Therefore a buffer is filled as and when data becomes available.
You must bear in mind that the result "might" not be complete. For example if a packet loss happens the result string might not be a complete XML. Therefore you need to do pre-checks without taking for gratis that the code is fool proof 🙂
Thank you DimaZ!
Your code worked beautifully. Thank you TekGirl for your advise!