Handling java.net.HttpURLConnection to server that does not exist - java

Upon trying to connect to a host/server that does not exist, my program just seems to die. Stepping through with the debugger lends me nothing, it makes it to getResponseCode() and then just stops working. No exceptions are thrown from what I can tell and the program doesn't return.
Here is the relevant code snippet:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
When connecting to a valid URL, it works fine.

I fixed it, I needed to add http.setConnectTimeout(10000); after I opened the connection. Apparently whatever the default timeout was set as was so long that it appeared to never give a response at all, even when leaving the application open for several minutes.

Related

Apache commons FPTSClient explicit transfer file is incomplete

Iam currently struggling a little bit with the FTPSClient from Apache Commons. See code down below. I try to write a file to FTP Server (vsftpd) when using FTPClient things are working perfectly fine. When using my code snippet I will always get a 451 Error, when debugging and waiting after Util.copyStream() returned everything works fine or settings a Thread.sleep(100). This also does not happen when I do not set the ftpsClient.execProt("P). Does anyone know by what this could be caused.
final FTPSClient client;
client = new FTPSClient("TLS", false);
client.setUseClientMode(true);
client.setDefaultPort(21);
// connect
try {
client.connect("serverAddress", 21);
} catch (SSLException e) {
throw e;
}
// setup any after connected
client.setSoTimeout(300);
client.setListHiddenFiles(true);
client.enterLocalPassiveMode();
FTPClientConfig ftpConfig;
try {
ftpConfig = new FTPClientConfig(client.getSystemType());
} catch (FTPConnectionClosedException e) {
throw e;
} catch (IOException e) {
ftpConfig = new FTPClientConfig();
}
client.configure(ftpConfig);
final FTPSClient ftpsClient = client;
// remove data buffer limit
ftpsClient.execPBSZ(0);
// set data channel encrypted
ftpsClient.execPROT("P");
client.login("user", "password");
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("Authentication failed: " + client.getReplyString().trim());
}
// postconfigure connection
if (!client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE) || !client.setFileType(FTP.BINARY_FILE_TYPE)) {
throw new IOException("Failed to correctly configure client: " + client.getReplyString().trim());
}
InputStream input;
OutputStream output;
input = new FileInputStream(pathToLocalFile);
output = client.storeFileStream("foobar.txt");
final var number = Util.copyStream(input, output);
System.out.println(number);
input.close();
// Thread.sleep(100);
output.close();
// Must call completePendingCommand() to finish command.
if (!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
This library has been around for a long time, and things change a bit under the hood. Try:
input = new FileInputStream(pathToLocalFile);
boolean result = client.storeFile("foobar.txt", input);
if (result) {
System.out.println("\tFile Transfer Completed Successfully");
}
I have noticed that every once in a while when transferring files to a mainframe, it won't complete. I think it has something to do with the file length, but I've never been able to track it down. I also don't use the stream_transfer_mode.

W/System: A resource failed to call end. When using HttpsURLConnection - Android

In the logcat I get a warning:
W/System: A resource failed to call end.
I am 100% positive that this piece of code makes the warning, since when I take it out it stops.
I can't seem to fix it so it doesn't display warning.
The purpose of the code is to check if there is internet connection or not.
It is on separate thread. Declared with:
public class ConnectWifiThread extends Thread {
public static boolean isInternetAvailable(Context context) {
Here is the code:
try {
URL url = new URL("https://www.google.com/");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setRequestProperty("User-Agent", "test");
https.setRequestProperty("Connection", "close");
https.setConnectTimeout(2000); // mTimeout is in seconds
https.connect();
int tempResponse = https.getResponseCode();
if (tempResponse == 200) {
https.disconnect();
Thread.sleep(50);
https=null;
url=null;
Thread.sleep(50);
Log.d("Has", "internet");
return true;
} else {
https.disconnect();
Thread.sleep(50);
https=null;
url=null;
Thread.sleep(50);
Log.d("NO", "internet");
return false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
catch (Exception e) {
Log.d("Error checking internet", e.getMessage());
return false;
}
Thank you
When you use a URLConnection, by default it makes an input stream for you to read the response. You'd get that by calling getInputStream() on the connection, and then you'd read the stream to completion and close it.
If you don't need the data, you can alternatively call setDoInput(false) to save you the trouble of doing the above.

DELETE Request in Android doesn't connect to server

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();

Java FTP over TLS/SSL (FTPS- Implicit) Server in Java - Several Error

I am trying to connecting a server with FTPSClient (true implicit), port 990, and it seems the connection is ok, but it says that the file PDF inside cannot be found.
String protocol = "TLS"; // TLS / SSL
boolean isImpicit = true;
int timeoutInMillis = 3000;
FTPSClient client = new FTPSClient(protocol, isImpicit);
client.setDataTimeout(timeoutInMillis);
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
try
{
int reply;
client.connect(server, port);
client.login(user, pass);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.execPBSZ(0);
client.execPROT("P");
System.out.println("Connected to " + server + ".");
reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
client.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
client.listFiles();
boolean retrieved = client.retrieveFile(Constantes.DIRECCION_FTP_PDF_FACTURAS + nombre_factura, new FileOutputStream(Constantes.DIRECCION_FTP_LOCAL_DESCARGAS + nombre_factura));
}
catch (Exception e)
{
if (client.isConnected())
{
try
{
client.disconnect();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
System.err.println("Could not connect to server.");
e.printStackTrace();
return;
}
finally
{
System.out.println("# client disconnected");
client.disconnect();
}
}
The error I got is java.io.FileNotFoundException
I tried writing the full path since C:\ , and without it, but nothing works.
Anybody can help me?
Thanks.
EDIT: IT WORKS NOW!
The path "Program Files" contains a space and maybe FileInputStream does not manage to resolve it properly.
May give it a try to put your folder to "C:/Temp/" and test it again.
Where does this FileNotFoundException happen exactly?

Check if URL is valid in Android without catching Exception?

See, I have to check like 50+ URLs for validity, and I'm assuming that catching more than 50 exceptions is kind of over the top. Is there a way to check if a bunch of URLs are valid without wrapping it in a try catch to catch exceptions? Also, just fyi, in Android the class "UrlValidator" doesn't exist (but it does exist in the standard java), and there's UrlUtil.isValidUrl(String url) but that method seems to be pleased with whatever you throw at it as long as it contains http://... any suggestions?
This solution does catch exceptions, however others may find it useful and doesn't require any libraries.
public boolean URLIsReachable(String urlString)
{
try
{
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
responseCode = urlConnection.getResponseCode();
urlConnection.disconnect();
return responseCode != 200;
} catch (MalformedURLException e)
{
e.printStackTrace();
return false;
} catch (IOException e)
{
e.printStackTrace();
return false;
}
}

Categories