This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Sockets and Internet Protocols and the fly likes Connection refused: connect Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark " Connection refused: connect" Watch " Connection refused: connect" New topic
Author Connection refused: connect

Ananth Venugopal

Joined: May 31, 2006
Posts: 2
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.

[ November 20, 2006: Message edited by: Ananth Venugopal ]

-- Ananth
Martin Simons
Ranch Hand

Joined: Mar 02, 2006
Posts: 196
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

Joined: Nov 02, 2006
Posts: 22
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 =, off, rd_nchars);
total += len;

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

if (len <= 0) {
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);

I agree. Here's the link:
subject: Connection refused: connect
Similar Threads
Access to website using Java Code
Connection refused on localhost
tomcat & netbeans Connection refused
Connection Refused Exception