Keep getting java.net.UnknownHostException after connecting to the internet - java

I'm using the Google HTTP Client Library for Java to develop a client application for a webservice of mine.
The problem is when I try to run some code like this:
private static void send() throws IOException {
HttpTransport httpTransport = new ApacheHttpTransport();
HttpRequestFactory httpRequestFactory = httpTransport
.createRequestFactory();
GenericUrl requestUrl = new GenericUrl("https://www.google.com/");
HttpRequest request = httpRequestFactory.buildGetRequest(requestUrl);
HttpResponse response = request.execute();
System.out.println(response.parseAsString());
}
public static void main(String args[]) throws InterruptedException {
boolean sent = false;
while (!sent) {
try {
send();
sent = true;
} catch (IOException e) {
e.printStackTrace();
Thread.sleep(1000);
}
}
}
I expected the program to keep trying to send the request each second until it's finnaly sent.
If I run the program with internet connected everything works fine.
If I disconnect from the internet and then run the program, I get a
java.net.UnknownHostException: www.google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:333)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.google.api.client.http.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:67)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at test.client.MyClass.send(MyClass.java:112)
at test.client.MyClass.main(MyClass.java:124)
as expected.
The problem is that I keep getting this exception even after I reconnect to the internet.
Any solutions?
Thanks
========================== UPDATE ==========================
The problem doesn't seem to be relate to the ApacheLibrary as it also happens when using the NetHttpTransport implementation.
Just replaced new ApacheHttpTransport(); by new NetHttpTransport(); on the code above generating a new looping stack trace:
java.net.UnknownHostException: www.google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:275)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:371)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at test.client.MyClass.send(MyClass.java:112)
at test.client.MyClass.main(MyClass.java:124)
Also I'm using a Fedora 20 Linux O.S. Kernel 3.16.6-200.
========================== UPDATE ==========================
Followed RealSkeptic's suggestion and debugged the code to find out where and how the DNS lookup is done.
I'm not familiar with java's low levew connection stuff, but I was able to produce the following almost equivalent code for the send function:
private static void send() throws IOException {
URL connUrl = new URL("https://www.google.com/");
URLConnection conn = connUrl.openConnection();
HttpURLConnection connection = (HttpURLConnection) conn;
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(false);
connection.addRequestProperty("Accept-Encoding", "gzip");
connection.addRequestProperty("User-Agent",
"Google-HTTP-Java-Client/1.19.0 (gzip)");
connection.setReadTimeout(20000);
connection.setConnectTimeout(20000);
boolean successfulConnection = false;
try {
connection.connect();
//NetHttpResponse response = new NetHttpResponse(connection);
successfulConnection = true;
} finally {
if (!successfulConnection) {
connection.disconnect();
}
}
}
It's lacking on the response treatment.
With the code above, I keep getting the same result: A looping stacktrace that never ends.
Does anyone knows how to solve that?
Some enviroment information:
$cat /etc/resolv.conf
# Generated by NetworkManager
domain velox.com.br
search velox.com.br
nameserver 208.67.222.222
nameserver 8.8.8.8
$ java -version
java version "1.7.0_71"
OpenJDK Runtime Environment (fedora-2.5.3.0.fc20-x86_64 u71-b14)
OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)

Related

get lantern VPN running and could get access to website, but use eclipse java app got connection timed out

Use lantern VPN, the chrome browser and eclipse have the same proxy and URL could get response but java code gets connection timed out.
The lantern VPN proxy:
Eclipse proxy:
The result for the url http://api.zb.com/data/v1/markets:
The code for get response:
String callback= "";
try {
// request url
String url = ZBConfig.API_DATA + "/markets";
log.info("markets configuration url: " + url);
// request call back
callback = HttpUtilManager.get(url, "UTF-8");
log.info("-markets configuration url:: " + callback);
} catch (Exception ex) {
ex.printStackTrace();
}
public static String get(String urlAll, String charset) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";// 模拟浏览器
try {
URL url = new URL(urlAll);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(30000);
connection.setConnectTimeout(30000);
connection.setRequestProperty("User-agent", userAgent);
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, charset));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
The error message from the console:
12:18:44.508 [main] INFO com.Test - markets configuration url: http://api.zb.com/data/v1/markets
java.net.ConnectException: Connection timed out: connect
12:19:06.095 [main] INFO com.Test - -markets configuration url:: null
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at com.zb.kits.HttpUtilManager.get(HttpUtilManager.java:353)
at com.Test.main(Test.java:201)
I had the same scenario in which I intended to bypass filtering which was applied on Youtube and instead of Lantern, I used to use Psiphon.
After running Psiphon it exposes a local port which you can use as proxy(and I'm sure Lantern is the same just check its log) and since it is applied as a system level proxy chrome can use it without any config, but if you wanna use it with Firefox you have to config it in the settings, and in order to use any proxy in your java codes you have to config jvm to use that proxy.
This is the sample code I used:
System.getProperties().put("http.proxyHost", Config.getHTTPPROXYHOST());
System.getProperties().put("http.proxyPort", Config.getHTTPPROXYPORT());
System.getProperties().put("https.proxyHost", Config.getHTTPSPROXYHOST());
System.getProperties().put("https.proxyPort", Config.getHTTPSPROXYPORT());
Also you can check the code in my github, in addition this post in stackoverflow can be quite useful.
hope it helps.

.getResponse Code Throwing IOException on a Valid URL

I'm building a webcrawler and have a method to check for bad link. At one point I am trying to get the HTTP response code to determine if it is valid or not. despite handing it a valid URL (opened it in a browser just fine) it still returns that it isn't valid. Here is the code:
public static boolean isBrokenLink(URL baseURL, String theHREF) {
boolean isBroken = false;
if (baseURL == null) {
try {
baseURL = new URL("HTTP", "cs.uwec.edu/~stevende/cs145testpages/", theHREF);
System.out.println(baseURL);
} catch (MalformedURLException e) {
isBroken = true;
//e.printStackTrace();
}
}
try {
URLConnection con = baseURL.openConnection();
HttpURLConnection httpProtocol = (HttpURLConnection) con;
System.out.println(httpProtocol.getResponseCode());
if (httpProtocol.getResponseCode() != 200 && httpProtocol.getResponseCode() == -1) {
isBroken = true;
}
} catch (IOException e) {
isBroken = true;
e.printStackTrace();
}
return isBroken;
}
}
And here is the URL I'm passing it. isBroken is the boolean that is being returned. I passing baseURL as null and theHREF as a relative link (page2.htm). I'm printing out the URL after creating it from the string. Thanks for any help!
Here is the error:
java.net.UnknownHostException: cs.uwec.edu/~stevende/cs145testpages/
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1300)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at edu.uwec.cs.carpenne.webcrawler.Webcrawler.isBrokenLink(Webcrawler.java:106)
at edu.uwec.cs.carpenne.webcrawler.Webcrawler.main(Webcrawler.java:181)
The exception tells us, that it is using the hostname and the local part as the (unknown) host. This looks like you have constructing the URL incorrectly. Maybe you forgot to use http:// prefix or used the wrong getters? You can debug it by calling baseURL.getHost(), baseURL.getPath() and baseURL.getProtocol() to see if it returns cs.uwec.edu and /~steve... and http.
I just noticed you added the baseURL with new URL("HTTP", "cs.uwec.edu/~stevende/cs145testpages/", theHREF) this is wrong, you need to use new URL("http", "cs.uwec.edu", 80, "/~stevende/cs145testpages/#"+theHREF). You can however typically skip the anchor/ref, as it will not transmitted to the server.
You can also use the single argument constructor new URL("http://cs.uwec.edu//~stevende/cs145testpages/").

Socket programming - Client (linux), server (Windows)

I'm trying to create simple socket application using sockets to send stream from linux (64x ArchLinux) to server (Windows XP).
Code I'm using I found on the internet, just to check if it is working. What is interesting the code works perfectly if I'm using Windows XP (server) and Win 8 (client), but when client is on ArchLinux it does not work. Is there some special way to connect Windows-Linux ?
Server.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Server_pzm {
public static void main(String args[]) {
String data = "Toobie ornaught toobie";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("192.168.224.78", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
// while (!in.ready()) {} line removed
System.out.println(in.readLine());
System.out.print("'\n");
in.close();
}
/* lines removed catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
} */
// added exception handling
catch(UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
EDIT
Sorry, I did not specify what I meant by not working. I meant I got an exception which later prints System.out.print("Whoops! It didn't work!\n"); as in the catch blok. Win 8 and Arch Linux are installed on the same laptop, while the code is on my dropbox folder in both systems (so the code is the same) - I will post the actual exception, after I get back to my laptop
EDIT 2:
I updated code and this is exception I got:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
java.net.ConnectException: Connection refused
This has two possible meanings.
There is nothing listening at the address:port you tried to connect to.
There is a firewall rule in the way.
More likely 1. Firewalls usually just drop the packets, which causes a connection timeout rather than a refusal.
Are you sure you can establish connection between those systems? I have compiled and run your code on Windows 7 and Linux Mint on Virtualbox and it works correctly.
What do you mean "It doesn't work"? Does it throw any exception? If you just don't have any output, try to run it again and wait about 30 seconds.
For me it's just a network problem. So you should also try to ping your windows machine from linux and then try to telnet to server.
Edit:
So we know it is a network problem. First try to ping ip server from Linux system.
ping 192.168.224.78
If it didn't work, you should check if both machines are in the same subnet 192.168.224.0 assuming the mask is 255.255.255.0. You need just to type ifconfig in console.
In next step you should try to disable windows firewall. Here is an instruction how to do that.

Java SSL javax.net.ssl.SSLException: Received fatal alert: internal_error

I finally managed to get SSL working between clients and my server... Atleast when running it directly from Netbeans.
Client network init code:
private Network(final String hostname, final int port) {
try {
URL resource = getClass().getResource("/truststore/TCGtruststore.jks");
if (resource == null) {
Controller.getInstance().write(MessageType.DEBUG, "Could not load trust store.");
throw new IllegalStateException("network.Network: Could not load trust store.");
}
else {
Controller.getInstance().write(MessageType.LOG, "Loaded trust store.");
}
System.setProperty("javax.net.ssl.trustStore", resource.getPath());
System.setProperty("javax.net.ssl.trustStorePassword", "tcgadmin");
Socket baseSocket = new Socket();
baseSocket.connect(new InetSocketAddress(hostname, port), Config.TIMEOUT);
SSLSocketFactory socketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
clientSocket = (SSLSocket)socketFactory.createSocket(baseSocket, hostname, port, true);
clientSocket.startHandshake();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
connected = true;
} catch (IOException ex) {
connected = false;
}
waitForServer = new HashMap<>();
}
Server network init code:
public Server(final int port) {
this.port = port;
try {
URL resource = getClass().getResource("/keystore/TCGkeystore.jks");
if (resource == null) {
throw new IllegalStateException("server.Server: Could not load key store.");
}
System.setProperty("javax.net.ssl.keyStore", resource.getPath());
System.setProperty("javax.net.ssl.keyStorePassword", "tcgadmin");
//serverSocket = new ServerSocket(port);
serverSocket = (SSLServerSocket)SSLServerSocketFactory.getDefault().createServerSocket(port);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
However when I clean and build it, and run it outside Netbeans, it breaks.
Surprisingly enough the client still behaves fine though, it is the server that starts acting strange with this message:
mei 20, 2013 4:36:16 PM server.ServerConnectionReceiver run
SEVERE: null
javax.net.ssl.SSLException: Received fatal alert: internal_error
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1977)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1093)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:882)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at server.ServerConnectionReceiver.run(ServerConnectionReceiver.java:45)
at java.lang.Thread.run(Thread.java:722)
Command line code from client:
[16:36:15] [Log] Loaded trust store.
[16:36:16] [Log] Could not establish a connection with the server.
Does anyone have any clue on what went wrong?
When server runs from within netbeans and client aswell, everything is fine.
When server runs from within netbeans and client via commandline, the server gives an exception.
When I try to run the server from commandline, it gives an error. (I was about to test if it would work with both from commandline, but I unfortunately cannot just test that)
Regards.

RabbitMQ "Hello World" example gives "Connection Refused"

II'm trying to make the "hello world" application from here: RabbitMQ Hello World
Here is the code of my producer class:
package com.mdnaRabbit.producer;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.io.IOException;
public class App {
private final static String QUEUE_NAME = "hello";
public static void main( String[] argv) throws IOException{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent" + "'");
channel.close();
connection.close();
}
}
And here what I get when implement this:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:445)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:504)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533)
at com.mdnaRabbit.producer.App.main(App.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 1
What is causing this?
I found the solution to my problem here Error in making a socket connection
To deal with it I installed RabbitMQ server. If rabbitmq-server is not installed this error will be thrown.
Make sure you have installed RabbitMQ server and it's up and running by hitting http://localhost:15672/
I got this "Connection Refused" error as well:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:588)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
at ReceiveLogs.main(ReceiveLogs.java:14)
I had made a mistake by setting the IP address from inside /etc/rabbitmq/rabbitmq-env.conf to the wrong ip address:
NODE_IP_ADDRESS=10.0.1.45
I removed this configuration parameter and the error goes away.
I solved this problem simply by executing:
sudo rabbitmq-server
Start the Rabbit MQ Server. The batch file to start this server is present under rabbitmq_server-3.6.0\sbin>rabbitmq-server.bat start then it will work.
In my case it gave me the following error trying to start the server
<Rabbit intall path>\rabbitmq_server-3.6.0\sbin>rabbitmq-server.bat start
ERROR: epmd error for host Protocol: inet_tcp: register/listen error: econnrefused: nxdomain (non-existing domain)
What I did was add in my host file the following line:
127.0.0.1 localhost
And then the rabbitmq-server started. After this I didn't get the connection refuse error anymore. Hope this helps.
Sometimes you just gotta reboot a mac. Tried all the other solutions here and other things from different questions, and as dumb as it sounds, a reboot is what finally got it back to running and able to reach http://localhost:15672/
This was after I had done a brew upgrade (which is what probably put me in a bad state).
You have to start Rabbit MQ Serever
In windows file name: RabbitMQ Service - start
You can use this code:
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class NewTaskController implements Runnable {
private final String message;
private static final String EXCHANGE_NAME = "test";
private static final String ROUTING_KEY = "test";
public NewTaskController(final String message) {
this.message = message;
}
#Override
public void run() {
//getting data from application.properties
//for the rabbit_mq configuration
ResourceBundle mRB = ResourceBundle.getBundle("application");
System.out.println("*****NewTaskController************"+mRB.getString("rabbitmq.port"));
String rabbitmq_username = mRB.getString("rabbitmq.username");
String rabbitmq_password = mRB.getString("rabbitmq.password");
String rabbitmq_hostname = mRB.getString("rabbitmq.hostname");
int rabbitmq_port = Integer.parseInt(mRB.getString("rabbitmq.port"));
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername(rabbitmq_username);
factory.setPassword(rabbitmq_password);
factory.setHost(rabbitmq_hostname);
factory.setPort(rabbitmq_port);
Connection conn;
try {
conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
String queueName = channel.queueDeclare().getQueue();
System.out.println(queueName);
channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);
System.out.println("Producing message: " + message + " in thread: " + Thread.currentThread().getName());
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes());
try {
channel.close();
} catch (TimeoutException e) {
e.printStackTrace();
}
conn.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
application.properties file:
rabbitmq.username=guest
rabbitmq.password=guest
rabbitmq.hostname=localhost
rabbitmq.port=5672
The simple fix is indeed, rabbitmq-server, if you already have RabbitMQ installed locally.
I encountered this issue as a firewall issue after migrating from Mac OS X Sierra to High Sierra. I already had RabbitMQ installed. However, I kept getting this Connection Refused error. I had to do the following:
brew uninstall rabbitmq
brew install rabbitmq
rabbitmq-server
(and allow firewall permissions)
Run app locally.

Categories