Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.net.ConnectException: Connection refused: connect

 
Ananth Venugopal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I'm trying to connect to a web page and fetch its contents and print the contents on to the console.

Here's the code that i've used:


But I'm getting the following Exception Stack Trace:



Can anyone suggest me how to get rid of this error.
Or is there any other method by which i can do the same.



Thanks in Advance.

-Ananth
[ November 20, 2006: Message edited by: Ananth Venugopal ]
 
Martin Simons
Ranch Hand
Posts: 196
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Connection refused normally means there was nothing listening on the port you tried to connect to, or possibly, that you tried to connect with the wrong protocol (i.e. http where https was required). Check your url and whether you should maybe be using HttpsUrlConnection rather than HttpUrlConnection.
 
Sushil Sharma
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ananth,
Your program has 2 issues: unable to connect to URL, and incorrect logic to read data into a buffer. I have modified your program and tested with localhost.
Note: use of Reader to read data directly as char instead of byte

public void getContent() throws IOException
{
URL url = new URL(this.url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();

// use a Reader to read stream as char instead of byte
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));

char[] chbuff = new char[1024];
StringBuffer contents = new StringBuffer();

// start number of read bytes from a small number
int rd_nchars = 32;
int total = 0;

// note: for loop is no
for (int i = 0, off = 0; rd_nchars > 0 {
int len = in.read(chbuff, off, rd_nchars);
total += len;

System.out.println(len + ", " + off + ", " + total);

if (len <= 0) {
System.out.println("done");
}
off += len;

rd_nchars = chbuff.length - off;

// not enough space left in chbuff
if (rd_nchars <= 0) {
System.out.println("done.. reached end of buffer");
}
}

System.out.println("Total chars read: " + total);

contents.append(chbuff, 0, total);

System.out.println(contents.toString());
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic