Java Read URL to String

Filed Under: Java
Java Read Url To String

In my current project, I had a requirement to read the WSDL file from the URL and store it into the database as CLOB.

There was no validation required, so it was kind of reading URL content to String and then storing it into the database table.

Java Read URL to String

Here is the program I wrote in java to read URL to String.



public class ReadURLToString {
	public static void main(String[] args) throws Exception {
		URL test = new URL("");
		URLConnection uc = test.openConnection();
		uc.addRequestProperty("User-Agent", "Mozilla/4.0");
		BufferedReader in = new BufferedReader(new InputStreamReader(uc
		String inputLine;
		StringBuilder sb = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {

		System.out.println("HTML Data:" + sb.toString());

When we run the above program, it produces the following output.

java read url to string

Most of the code is self-understood except setting the user agent. For some websites, if you don’t set User-Agent header, you might get 403 error code. Just comment it in above program and you will get below error.

Exception in thread "main" Server returned HTTP response code: 403 for URL:
	at ReadURLToString.main(

If you have landed here and looked for something similar, feel free to use the above code and don’t forget to comment or share with others. That’s all for reading URL content in java program.

Reference: Java URLConnection API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages