I'm havin this situation. I have server running in CentOS (CentOS is in my virtual machine VMware). In host (win7) I have java program that needs to make GET method to server on CentOS. I've manage connection between host and virtual machine and thing works from browser and java program in CentOS and from browser in host (win7) but not from java program in host which is what I need.
If I turn off virtual machine I still get timeout exception.
I've turn off firewall on win7 but i can't turn it off in CentOS because I don't have admin permission.
This is my java code for GET method (192.168.11.128 is IP of virtual machine) :
private static void getMethod(){
// Create a method instance.
GetMethod method = new GetMethod("http://192.168.11.128");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
Thanks for any help!
Related
I would like to connect by TCP to a machine given its IP address and its port.
I decided to use the JAVA java.net.Socket class and its connect method as it seems to fit my need.
For testing purpose, as the machines I need to test are not yet available, I tried to connect a local machine on its standard port 80.
But I was very surprised to see that it succeeded with any IP address, even an unknown one: I cannot "ping" it, but the connect method gives me success...
Did I missed something in JAVA Socket understanding?
How is this behaviour possible?
Here is my code :
private void testSocketConnection() {
try (Socket socketToMachine = new Socket()) {
InetSocketAddress address = new InetSocketAddress(InetAddress.getByName("1.2.3.4"), 80);
socketToMachine.connect(address, 1000);
System.out.println("SUCCESS");
} catch (UnknownHostException uhe) {
System.out.println("UnknownHostException");
} catch (IOException ioe) {
System.out.println("IOException");
}
}
I'm creating an app which generates a CSV file and some PDFs. I want my app to send those files to a server via FTPS protocol.
I'm using Apache Commons Net FTP library and it was perfectly working when I had "Require TLS session resumption on data connection when using PORT P" unchecked, but since I enabled it I can't send my files.
An error appeared :
450 TLS session of data connection has not resumed or the session does not match the control connection.
After some researches on this site I have overriden _prepareDataSocket_ in order to overcome this problem but now it just creates empty files on the server.
There is my overriden function :
#Override
protected void _prepareDataSocket_(final Socket socket) throws IOException {
if (socket instanceof SSLSocket) {
// Control socket is SSL
final SSLSession session = ((SSLSocket) _socket_).getSession();
if (session.isValid()) {
final SSLSessionContext context = session.getSessionContext();
try {
final Field sessionHostPortCache = context.getClass().getDeclaredField("sessionHostPortCache");
sessionHostPortCache.setAccessible(true);
final Object cache = sessionHostPortCache.get(context);
final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
method.setAccessible(true);
method.invoke(cache, String
.format("%s:%s", socket.getInetAddress().getHostName(), String.valueOf(socket.getPort()))
.toLowerCase(Locale.ROOT), session);
method.invoke(cache, String
.format("%s:%s", socket.getInetAddress().getHostAddress(), String.valueOf(socket.getPort()))
.toLowerCase(Locale.ROOT), session);
} catch (NoSuchFieldException e) {
throw new IOException(e);
} catch (Exception e) {
throw new IOException(e);
}
} else {
throw new IOException("Invalid SSL Session");
}
}
}
and this is what FileZilla Server displays:
FileZilla Response
will this answer on another forum help?
http://forum.rebex.net/5673/450-error-connecting-to-ftp-requiring-explicit-ftp-over-tls
I use NCache java API for connecting to NCache server but it throws an exception:
com.alachisoft.ncache.runtime.exceptions.GeneralFailureException: No server is available to process the request.
I also tried some suggestion from this site
but cannot solve the problem.
Here are the java codes.
String cacheId = "mycache";
try {
cache = NCache.initializeCache(cacheId);
} catch (Exception ex) {
ex.printStackTrace();
log.log(Level.SEVERE, "NCacheConnection()", ex.getMessage());
}
I am coding a web server in Java and so far everything is working nicely. However, since I am unable to obtain a SSL Certificate to test with, I do not have a way to test my server over https. Except for the following code, my server is written to respond to https requests the same way as it does with http requests. Would it work?
System.setProperty("javax.net.ssl.trustStore", trustStorePath);//The path to the trust store file
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);//The trust store password
try(SSLServerSocket socket = (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(ssl_listen_port)) {
socket.setReuseAddress(true);
System.out.println("\tServer SSL socket created on port " + ssl_listen_port);
while(serverActive) {
//Omitted multithreading code for read-ability:
final SSLSocket s = (SSLSocket) socket.accept();
try {
s.startHandshake();
} catch(SSLHandshakeException e) {
System.err.println("Failed to initialize SSL handshake: " + e.getMessage());
continue;
}
//(The server then handles the remainder of the request as if it were http.)
}
} catch(BindException e) {
System.err.println(" /!\\\tUnable to bind to ssl port " + ssl_listen_port + ":\r\n/___\\\t" + e.getMessage());
} catch(Throwable e) {
e.printStackTrace();
}
I apologize in advance if this sort of question has already been asked or if I have done something wrong.
I am trying to connect android device with laptop or desktop which contains Bluetooth via Bluetooth socket connection.
I have created one android application (Client) which tries to connect laptop Bluetooth device where java application (Server) is running.
My concern is that, Is it possible to connect both the device insecurely (without pin authentication) using Bluetooth socket connection?
If possible, Please suggest me solution.
If not, Is there any way to programmatically auto pair both the devices?
Thanks in advance !!!
By referring java api for bluetooth, I got the solution for Insecure connection between two Android and laptop Bluetooth devices.
I have used SPP client server mechanism.
My server is in java.
In java add certain parameters to URL.
Make authentication= false; authorize=false;encrypt=false;
open this URL for connection acceptance.
//Create a UUID for SPP
UUID uuid=new UUID("0f2b61c18be240e6ab90e735818da0a7", false);
System.out.println("\n"+uuid.toString());
//Create the servicve url
String url="btspp://localhost:"+uuid.toString()+";"+"name=remoteNotifier;authenticate=false;authorize=false;encrypt=false";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open(url);
//Create a UUID for SPP
UUID uuid=new UUID("0f2b61c18be240e6ab90e735818da0a7", false);
System.out.println("\n"+uuid.toString());
//Create the servicve url
String url="btspp://localhost:"+uuid.toString()+";"+"name=remoteNotifier;authenticate=false;authorize=false;encrypt=false";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open(url);
Now on client side:
Android API 10 above contains insecure connection method. "createInsecureRfcommSocketToServiceRecord(UUID)"
So use this method for connection. It will not pop up for pairing request adn try to connect with remote Bluetooth device where Java server is already running.
Code:
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
// btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
mBluetoothAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android_logo);
// byte[] msgBuffer = getBytesFromBitmap(bitmap);
String message = "Hello from Android.\n";
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00")) {
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
}
// AlertBox("Fatal Error", msg);
}
I have provided only required code.
For connection UUID should be same for both the devices.
Provide server Bluetooth MAC address at "address" field at client side.
We are able to communicate with remote Bluetooth device insecurely (Without pairing).
But this code is device dependent...
certain device are able to communicate very efficiently.
Like Lenovo laptop, external bluetooth device for PC for Java server
AND
Android devices DELL venue 7, Sony, LG mobiles for client.
Tested and working properly.
But in Dell laptop, Micromaxx, xolo mobile it doesn't work.
I don't know why it is not working, If anyone knows please give the solution.
For Bluetooth 2.1 and above devices, security is mandatory.
If you are just trying to avoid the passkey entry/display, you can set the security requirements on the laptop and android device to "MITM protection not required".
This way the devices will pair automatically, but the link would be susceptible to man in the middle attacks.