Wiremock proxy stub runs on port 1234 with host http://example.com, but httpURLConnection.getResponseCode() gives connection refused error.
wireMockServer.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://example.com:1234")));
ConnectionFactory conFac = new ConnectionFactory("http://example.com", 1234);
HttpURLConnection httpURLConnection = conFac.getHttpURLConnection(new URL(new URI("http", null, "http://example.com", 1234, null, null, null).toString()));
httpURLConnection.getResponseCode();
If you want to use WireMock to act as a proxy of http://example.com, then you missunderstand what proxiedFrom stand for. It's used for forwarding your request received by your local wiremock server to the other website. For example, you set up wiremock running on localhost:8888. Then, you set up something like proxiedFrom("example.com"). As a result, what ever sending to localhost:8888/rooms/{id} will be forwarding to example.com/rooms/{id}.
WireMock proxy Documentation
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().proxyVia("http://example.com", 79));
Tried proxyVia()... httpURLConnection.getResponseCode(); gives java.net.ConnectException: Connection refused
ConnectionFactory conFac = new ConnectionFactory("http://example.com", 1234);
HttpURLConnection httpURLConnection = conFac.getHttpURLConnection(new URL(new URI("http", null, "http://example.com", 1234, null, null, null).toString()));
httpURLConnection.getResponseCode();
It is 1234 and not 79. Still throws ConectException
WireMockServer wireMockServer = new WireMockServer(wireMockConfig().proxyVia("http://example.com", 1234));
Related
I am trying to call some external API hosted on azure from my web Api. The API is working fine on my local machine but when I deploy it IIS on server it starts throwing System.Net.Sockets.SocketException (10060).A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Although I have increased the request timeout to 5 minutes but connection is silently stopping after 21 seconds and throwing aforementioned exception.
Here is my code:
var telemetries = new TelemetryResponse();
var client = httpClientFactory.CreateClient("Lynx");
client.Timeout = TimeSpan.FromMinutes(5);
var httpResponseMessage = await client.GetAsync("vehicletelemetries/All?key=iLJIbAVXOnpKz5xyF0zV44yepu5OVfmZFhkHM7x");
if (httpResponseMessage.IsSuccessStatusCode)
{
string content = await httpResponseMessage.Content.ReadAsStringAsync();
telemetries = JsonConvert.DeserializeObject<TelemetryResponse>(content);
}
Exception I am getting is:
System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
You got an error code:
WSAETIMEDOUT
10060
Connection timed out.
A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2#WSAETIMEDOUT
Check your network connection, ip adress, port and maybe the connection got blocked from a firewall.
Hi guys the culprit was the proxy and we have to configure our HttpClient with proxy while creating it/registering in the DI container. I have registered the HttpClient in DI like this.
var proxySettings = new ProxySetting();
Configuration.Bind(nameof(ProxySetting), proxySettings);
services.AddHttpClient("Lynx", client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy(proxySettings)});
And my proxy code is
public class MyProxy : IWebProxy
{
private readonly ProxySetting _proxySetting;
public MyProxy(ProxySetting proxySetting)
{
_proxySetting = proxySetting;
}
public ICredentials Credentials
{
//get { return new NetworkCredential("username", "password"); }
get { return new NetworkCredential(_proxySetting.UserName, _proxySetting.Password,_proxySetting.Domain); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri(_proxySetting.ProxyUrl);
}
public bool IsBypassed(Uri host)
{
return false;
}
}
It has resolved my problem completely.
I am using .Net Core 3.1 and Hangfire MongoDb for background scheduling, now on startup it is throwing
Autofac.Core.DependencyResolutionException: An exception was thrown while activating λ:Hangfire.IGlobalConfiguration.
---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.
---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Authentication.SaslAuthenticator.Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken
My Connection string in the config file is correct and I am able to connect to the DB from the same connection string through the Mongo Client
"ConnectionStrings": {
"MongoJobSchedulerConnection": "mongodb://user:password#ipaddress:port/DbName"
}
This is how I am adding Hangfire in Startup.cs
var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
services.AddHangfire((sp,configuration) => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseActivator<JobActivator>(new SchedulerJobActivator(sp.GetRequiredService<IServiceScopeFactory>()))
.UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, new MongoStorageOptions
{
MigrationOptions = new MongoMigrationOptions
{
MigrationStrategy = new MigrateMongoMigrationStrategy(),
BackupStrategy = new CollectionMongoBackupStrategy()
},
Prefix = "SchedulerQueue",
CheckConnection = true
})
);
any hint on the issue will be a great help
Thank You
The reason for this was MongoDB authentication was not happening against the admin DB somehow
This can be fixed by adding auth source to connection string like
"ConnectionStrings": {
"MongoJobSchedulerConnection": "mongodb://user:password#ipaddress:port/DbName?authSource=admin"
}
or this can be specified in MongoUrlBuilder like
var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
mongoUrlBuilder.AuthenticationSource = "admin";
I have a Scala app that runs an akka-http webserver on a custom port, let's say 8000.
Until a while ago, it would only handle http:// requests, but recently I switched to https://.
Some of the clients have the link bookmarked and keep getting the no connection error because they try the address with http:// instead of https:// and they keep forgetting why it happens.
I tried binding two services to the same port but failed because only the first one gets binded.
Http().bind(interface = "0.0.0.0", port = Global.settings.restPort, connectionContext = httpsContext)
Http().bind(interface = "0.0.0.0", port = Global.settings.restPort)
All I need from the http:// server is to return a 301 code and redirect to the same address, but with https protocol.
How can I achieve that?
As others have commented, you can't bind the HTTP and HTTPS servers to the same port. You can have both servers running on separate ports and redirect all HTTP traffic to the HTTPS server using Akka-http's scheme() and redirect():
val hostName = "www.example.com"
val portHttp = 8080
val portHttps = 8443
val route =
scheme("http") {
extract(_.request.uri) { uri =>
redirect( uri.withScheme("https").withAuthority(hostName, portHttps),
StatusCodes.MovedPermanently
)
}
} ~
pathSingleSlash {
get {
complete( HttpEntity( ContentTypes.`text/html(UTF-8)`,
"Welcome to Akka-HTTP!"
) )
}
}
Http().bindAndHandle(route, hostName, portHttp)
Http().bindAndHandle(route, hostName, portHttps, connectionContext = httpsContext)
Note that there is no need for applying withAuthority() if you're using standard HTTP and HTTPS ports (i.e. 80 and 443).
I am getting the following error when setting up an email service with spring boot while trying to connect to round cube:
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
This leads me to think roundcude is not using a SSL connection and I should not use port 143. Therefore I try and use port 25, but I get the following error when I do.
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
application.properties
#email setup
spring.mail.host = mail.email address.com
spring.mail.username = email address
spring.mail.password = my password
spring.mail.properties.mail.smtp.auth= true
spring.mail.port = 25 or port 145
spring.mail.properties.mail.smtp.socketFactory.class= javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback= false
spring.mail.properties.mail.smtp.ssl.enable = true
Email service
#Component
public class EmailServiceImpl implements EmailService {
#Autowired
private JavaMailSender javaMailSender;
#Override
public void sendEmail(String toAddress, String fromAddress,
String subject, String body) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(fromAddress);
simpleMailMessage.setTo(toAddress);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(body);
javaMailSender.send(simpleMailMessage);
}
}
I looked at roundcube's documentation and apparently is uses port 143 so this is rather confusing. This making me think I am setting this up wrong.
I also tried gmail but since I have a two factor authentication I ran into more issue so I decided to use roundcube which is what I would rather use anyway.
Advice?
It seems you're trying to connect to SMTP using non-secure ports. Usually secure ports would be 587 or 465.
This is the configuration that works for me to send e-mail using GMail:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=my-email#gmail.com
spring.mail.password=my-password
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.connectiontimeout = 60000
spring.mail.properties.mail.smtp.timeout = 60000
Im trying to connect to Openfire Server using Asmack library 4.0.2.Im failing to get connected to the server even though i had provided correct ip address with the port.
public static final String HOST = "192.168.1.100";
public static final int PORT = 9090;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect();
}
public void connect(){
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... arg0){
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST,PORT);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.disabled);
config.setDebuggerEnabled(true);
XMPPConnection connection = new XMPPTCPConnection(config);
try{
connection.connect();
Log.i("XMPPChatDemoActivity","Connected to " + connection.getHost());
isConnected = true;
} catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+connection.getHost()+"Port:"+connection.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return isConnected;
}
};
connectionThread.execute();
}
And im getting the following error possibly because Host and Port are getting assigned null and 0 respectively even though i had assigned them correctly.Pls help me in
sorting out this connection prob.
08-12 22:10:20.496: E/XMPPSmackException(4341):org.jivesoftware.smack.SmackException$NoResponseException Host:nullPort:0
Can you confirm that port 9090 is the correct port for XMPP protocol? Default install of Openfire will set port 9090 to be used for accessing the HTTP based configuration console. I recommend you try connecting to the port for XMPP connections as specified on the main index page of the Openfire configuration console (Listed below "Server Ports").
The following is taken from the Openfire configuration console:
5222 The standard port for clients to connect to the server. Connections may or may not be encrypted. You can update the security settings for this port.
I think your Host adress is wrong too, you must use the adress to connect openfire server. It must be "127.0.0.1" or just write "localhost". and the port is 5222 to be able to talk from client to server.