Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get url html contents to string in java

I have a html file stored on the server. I have the URL path something like this: <https://localhost:9443/genesis/Receipt/Receipt.html >

I want to read the contents of this html file which would contain tags, from the url i.e. the source code of the html file.

How am I supposed to do this? This is a server side code and can't have a browser object and I am not sure using a URLConnection would be a good option.

What should be the best solution now?

like image 794
Peyush Goel Avatar asked Jun 18 '12 16:06

Peyush Goel


2 Answers

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
public class URLContent {
    public static void main(String[] args) {
        try {
            // get URL content
            
            String a = "http://localhost:8080//TestWeb/index.jsp";
            URL url = new URL(a);
            URLConnection conn = url.openConnection();
 
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));
 
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                System.out.println(inputLine);
            }
            br.close();
 
            System.out.println("Done");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
like image 154
Vaibs Avatar answered Nov 17 '22 08:11

Vaibs


Resolved it using spring added the bean to the spring config file

  <bean id = "receiptTemplate" class="org.springframework.core.io.ClassPathResource">
    <constructor-arg value="/WEB-INF/Receipt/Receipt.html"></constructor-arg>
  </bean>

then read it in my method

        // read the file into a resource
        ClassPathResource fileResource =
            (ClassPathResource)context.getApplicationContext().getBean("receiptTemplate");
        BufferedReader br = new BufferedReader(new FileReader(fileResource.getFile()));
        String line;
        StringBuffer sb =
            new StringBuffer();

        // read contents line by line and store in the string
        while ((line =
            br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        return sb.toString();
like image 33
Peyush Goel Avatar answered Nov 17 '22 09:11

Peyush Goel