Gabriel Matusevich
Gabriel Matusevich

Reputation: 3855

Java HttpUrlConnection throws Connection Refused

I know there are several question regarding this topic But I did't find an answer in any of them.

I'm trying to open a connection to my local server but I keep getting connection refused.

I have the server running and I tested the connection with the Browser and with a Google App called Postman and it works.

It's failing when opening the connection as if there where nothing to connect to. or maybe something is blocking the connection? I tested with firewall and antivirus down, no luck.

testing in Postman the URL returns a User as it should...

If I replace the url with "http://www.google.com" It Works fine.

here is my code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *
 * @author Gabriel
 */
public class HttpConnection {

    public HttpConnection() {

    }

    public void makeRequest() throws MalformedURLException, IOException {

        String url = "http://localhost:8000/users/1";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6");
        con.setRequestProperty("Connection", "keep-alive");
        con.setRequestProperty("Host", "localhost:8000");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());


    }
}

Upvotes: 10

Views: 15890

Answers (7)

SalkinD
SalkinD

Reputation: 783

I faced exactly the same problem. Use this instead of localhost:

http://[::1]:8000/index.php

Upvotes: 7

somprabhsharma
somprabhsharma

Reputation: 323

You can try implementing CORS at the API you are trying to connect by setting access-control-allow-origin:* property in response header.

Upvotes: 2

David Cain
David Cain

Reputation: 166

I have similar code that is working, but my request header is a lot simpler. Basically just:

con.setRequestProperty("User-Agent", "Mozilla/5.0");

If simplifying the header does not help, I would capture the traffic when using your browser with something like fiddler and then making the request look exactly like that.

Upvotes: 3

rsabir
rsabir

Reputation: 736

The code is good and works great. Now the problem must be on the transportation or network part. What I want to mean is you don't request the right server. If you use 127.0.0.1 instead of localhost I think you won't get a problem. So, my guest will be that you have a problem in /etc/hosts or C:\Windows\System32\drivers\etc\hosts.

I advice you to try a simple test: ping the hostname and check in the output if the ip address is good.

Upvotes: 1

Jackson Hurt
Jackson Hurt

Reputation: 312

You mentioned that you were opening a connection to your "local server" I am assuming that you are doing this on the same computer that you're hosting the server on?

  • Try to open the connection to your local server using a different computer.

Upvotes: 0

R1D1CUL3
R1D1CUL3

Reputation: 41

Well, put http://localhost:8000/users/1 in your web browser and what do you get? A simple Connection Refused error. It's not you, it's the website. Also, Url returns websites using Protocol Identifiers(http://, https://), Ending Domains(.com, .edu, .gov) that's also another reason why you get an error.

Upvotes: 0

gustf
gustf

Reputation: 2017

I will make a wild guess what can be the problem. It is possible a IPv4/IPv6 problem.

If so, here is two possible solutions

  • If the server is only listening on an ipv6 address, change it to listening to ipv4.
  • If the server is listening to ipv4, then force Java to use ipv4 with java.net.preferIPv4Stack=true

Upvotes: 2

Related Questions