How to connect to server using https by socketrocket - socketrocket

I'm using socketrocket to connect to a server, everything's ok with http.
My question: how to connect to server using https by socketrocket

When you start the client program, the server should already be running and listening to the port, waiting for a client to request a connection. So, the first thing the client program does is to open a socket that is connected to the server running on the specified host name and port:
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
)
Note: For Above code to work, you have to know the server port.
But you can also access https using the below code:
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
URL url = new URL("https://www.verisign.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}

Related

How to make HttpClient relay traffic show up in Fidder or Charles?

I have a simple web api project based on this example:
http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/RelaySample/Program.cs
However, in the above sample the relay is working with a local server, in my project the relay is working with an external web server with a real address; companyX.com
I am using the relay service (or, web proxy service) through a browser, for example, in the browser request relayService.com/companyX. The relay service responds with data from the external companyX.com site.
The relay works great, however some headers are not correct and I need to see what the HttpClient is sending to the remote companyX.com server.
In fiddler or Charles, only the request/response from my browser to relayService.com is listed, the request/response from the HttpClient to relayService.com never shows up.
The relayService.com is running locally on my machine, in IIS7, I'm using the hosts file to direct traffic to relayService.com.
I have tried several variation of the following when creating the HttpClient:
var clientHandler = new HttpClientHandler
{
CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
UPDATE
If I change UseProxy = false The service continues to work, when Fiddler is open or closed.
With UseProxy = true then the service will fail, if fiddler is open, I get the following error:
Object reference not set to an instance of an object.
at System.DomainNameHelper.IdnEquivalent(String hostname) at System.Net.HttpWebRequest.GetSafeHostAndPort(Uri sourceUri, Boolean addDefaultPort, Boolean forcePunycode) at System.Net.HttpWebRequest.GenerateProxyRequestLine(Int32 headersSize) at System.Net.HttpWebRequest.SerializeHeaders() at System.Net.HttpWebRequest.EndSubmitRequest() at System.Net.Connection.CompleteConnection(Boolean async, HttpWebRequest request)
With UseProxy = true and fiddler is CLOSED, I get the following (obvious) error:
No connection could be made because the target machine actively refused it 127.0.0.1:8888
In the same solution I am using HttpWebRequest to download data from the web and that does show up in Fiddler, so it seems to be an issue with the HttpClient.GetAsync()
I have tried this on two machines with identical results.
I have been struggling with this all day, any help would be much appreciated.
Just to recap:
* relayService.com is running locally on my machine, in IIS7
hosts file has "127.0.0.1 relayService.com"
relayService.com is an MVC Web API site that uses HttpClient.GetAsync() to download content from the live web
Fiddler/Charles is running locally on same machine
browser traffic to the local relayService.com appears in Fiddler/Charles
HttpClient.GetAsync() to live web traffic does not appear in Fiddler/Charles
Fiddler/Charles are both up to date versions.
Thanks again
You don't need anything in your HOSTS file if you're using Fiddler; you can use Fiddler's Tools > HOSTS to redirect traffic anywhere you'd like.
When trying to capture traffic from a service account (e.g. the ASP.NET acccount) you typically want to configure that account to use the proxy; see http://fiddler2.com/blog/blog/2013/01/08/capturing-traffic-from-.net-services-with-fiddler for details on that. If you do that, you shouldn't need to configure the proxy object directly in code.
The exception you've shown suggests that here's a bug in the GenerateProxyRequestLine function. Is there any change if you update this: new WebProxy("http://localhost:8888"); to new WebProxy("127.0.0.1", 8888); ?
Generally speaking, .NET applications will bypass the proxy for URLs pointed at //localhost or //127.0.0.1, so when debugging with Fiddler it's common to use a service URL of //localhost.fiddler so that the traffic is always sent to the proxy.
I fixed the problem by making the HttpClient static.
This works fine (for the program functionality) but has the problem with fiddler described above, where trying to use the proxy throws an error:
private HttpClient _client()
{
var clientHandler = new HttpClientHandler
{
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = true,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
client.Timeout = TimeSpan.FromMinutes(20);
return client;
}
The client was created with:
using (HttpResponseMessage serviceResponse = await _client().GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
However, the below also works and all traffic shows up in Fiddler!
private static readonly HttpClientHandler _clientHandler = new HttpClientHandler()
{
//CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = false,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic,
};
//Create a shared instance of HttpClient and set the request timeout
private static readonly HttpClient _client = new HttpClient(_clientHandler)
{
Timeout = TimeSpan.FromMinutes(20)
};
The client was created with (only difference is removing the '()' after _client above):
using (HttpResponseMessage serviceResponse = await _client.GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
I have no clue why this works. Any insight would be appreciated.
Thanks,

No FtpWebRequest.GetResponse with IIS 7.5 and Firewall on but with Visual Studio 2010 Webserver and IIS Express 8

A MVC4 application downloads files from a FTP-Server in a action from HomeController. With the visual Studio 2010 Webserver and the local webserver IIS Express 8 it works.
But when I use the local webserver IIS 7.5 with ApplicationPoolIdenty, the download doesn't work: I don't received a respond on the line with the command "response = reqFTP.GetResponse()" and follow exception appears: "The operation has timed out").
When I switch off the Windows-Firewall, it works. What I need to do?
Function FtpStart() As ActionResult
Dim downloadFiles As String()
Dim result As New StringBuilder()
Dim response As WebResponse = Nothing
Dim reader As StreamReader = Nothing
Try
Dim reqFTP As FtpWebRequest
reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://adress")),FtpWebRequest)
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "pw")
reqFTP.EnableSsl = False
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
reqFTP.Proxy = Nothing
reqFTP.KeepAlive = False
reqFTP.UsePassive = False
Debug.WriteLine("Get Response: ")
response = reqFTP.GetResponse()
Debug.WriteLine("Response received")
reader = New StreamReader(response.GetResponseStream())
Dim line As String = reader.ReadLine()
While line IsNot Nothing
result.Append(line)
result.Append(vbLf)
line = reader.ReadLine()
Debug.WriteLine("File: " & line)
End While
result.Remove(result.ToString().LastIndexOf(ControlChars.Lf), 1)
Return RedirectToAction("Index")
Catch ex As Exception
Debug.WriteLine(ex.ToString())
Return RedirectToAction("Index")
End Try
End Function
ran into this issue earlier today myself on my web server. You have to setup a rule on your firewall for inbound rules on TCP for ports 20 and 21. It should show Local port = all ports, and remote ports = 20-21. Also make sure that on the advanced tab, all three checkmarks are checked for domain, private, and public. My firewall already had a FTP firewall rule for port 21, but not 20, as soon as I set the rule for port 20, it worked.
Hope this helps

How to include network credentials in Neo4JClient?

So tipically if you install Neo4j in your development environment, you will have a local hosted version of the Neo4Jserver, which usually you can browse with: localhost:7474/db/data.
Your code is like this:
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
However, one day you will want to connect to your Cloud-based Neo4J Server (Heroku, Azure, etc.)
Of course, that means you will have to provide Network credentials.
If you only use your bare hands, it could be like this:
var http = (HttpWebRequest)WebRequest.Create(new Uri("http://<<your_REST_query"));
var cred = new NetworkCredential("yourusername", "yourpassword");
http.Credentials = cred;
var response = http.GetResponse();
var stream = response.GetResponseStream();
But how can I include network credentials to connect with Neo4JClient? or is there another option that I don't know?
We support the standard URI syntax for basic authentication credentials:
var client = new GraphClient(new Uri("http://user:pass#localhost:7474/db/data"));
From version 1.1.0.0
var username = "app_username"
var password = "1#mGr#phG0d"
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), username, password);

Communicate Two Jar File [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
First of all I am new in Java. I hope that you would interest on that question, but please make your answers as obvious as possible. And I will try to tell my problem in an open way.
I am using NetBeans. I want to communicate two jar files such a way that,lets i have two jars A and B. And they are both in process, that is they are executed separately and I see two opened window. In the window of jar A, it waits for a string from user and I write there "call B". Then in the window of jar B, it will say that "program A is called at ... ". I searched on Internet and I have found such staff;"java.util.jar.JarFile, Remote Method Invocation, Network Sockets etc". But I could not reach any result from them since i could not find understandable answers for beginners. So if you suggest one of them, please give me at least a small example showing how to use them.
For a simple form of communication you could use java.net.socket to communicate between the two jar files. This will allow you to have the "ping pong" effect you desire.
In programA you would setup the server socket and listen for a client to connect
try {
serverSocket = new ServerSocket(4567);
}
catch (IOException e) {
System.out.println("Could not listen on port: 4567");
System.exit(-1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println("Accept failed: 4567");
System.exit(-1);
}
If the server is able to accept a client the clientSocket object will have the remote address and remote port set to that of the client.
After the server successfully establishes a connection with a client, it communicates with the client (program B) using this code:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
out.println("ping");
while ((inputLine = in.readLine()) != null) {
System.out.println("Program B says: " + inputLine);
out.println("server: " + inputLine);
if (inputLine.equals("quit"))
break;
}
Now you have written the logic for program A to be able to talk to program B you also need to create the client to be able to interact with it.
ProgramB:
Socket socket = new Socket("programb", 4567);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader sysIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("server: quit"))
break;
fromUser = sysIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
Then for good practice close the streams
out.close();
in.close();
sysIn.close()
socket.close();
And this should give you a basis to be able to talk between the two, you will probably need to implement some form of protocol (something to handle messages) on the server so that it outputs something useful
Reference: http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html

Blackberry Network connection

Trying to connect via Wi-Fi and I have an issue with the OS6 cd variable is null but it works on OS5
This is the url Strng: https://api3.popfax.com/index.php?service=Popfax;interface=wifi;interface=wifi
public ServiceConnectionBlackBerry(String s) throws IOException {
ConnectionFactory cf = new ConnectionFactory();
ConnectionDescriptor cd = cf.getConnection(s);
if (cd!=null){
connection = (HttpConnection) cd.getConnection();
}else {
System.out.println("Strng: "+s);}
}
can someone help please.
When using ConnectionFactory you should not append any connection information to your URL. So instead you should just pass https://api3.popfax.com/index.php?service=Popfax to your method.
Open a Wi-Fi HTTPS connection may help you.
thanks

Resources