HI can anybody tell me how to create a file and write on it on the URl.
Actually I am using an applet and from theat I want to create a file on
getCodebase(); so can any body tell me how can I do it
I have tried
URL url = new URL(/*url by codebase and the directory with file name*/);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
but it not worked
Please help me
Actually I am using an applet and from theat I want to create a file on getCodebase();
Well that wouldn't be very secure if you could do that, would it?
I think the route you want to take is to configure your HTTP server to handle PUT requests, and then form a PUT in Java. That is described here:
How to send PUT, DELETE HTTP request in HttpURLConnection?
However, your applet probably needs elevated permissions (in other words, a signed applet that operates outside of the normal sandbox). I'm not sure about that though; some connections are allowed back to the host so you might be OK.
Related
My goal is to to convert a .txt file on an FTP page to a simple String for easy manipulation.
The specific .txt file is here: ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt. It is an anonymous FTP page, so when I use my computer's browser, there's no need for a username or password.
I've tried incorporating different codes and tips from the following sources:
Reading Text File From Server on Android
http://examples.javacodegeeks.com/core-java/apache/commons/net-commons/download-file-from-ftp-server/
How to read a text file via FTP?
Reading txt file from an ftp server and returning it from AsyncTask
unable to read file from ftp in android?
Howto do a simple ftp get file on Android
http://www.javaworld.com/article/2073325/java-app-dev/java-ftp-client-libraries-reviewed.html
http://developer.android.com/reference/java/net/URLConnection.html
None of what I've tried above helped. I'm not quite sure what I'm doing wrong.
To be clear, all I want to do is to get the plain text from the posted .txt file. I have no interest in downloading said file onto my device's memory.
If you could provide me with a step-by-step explanation on how to do this, I'd be very thankful.
Ok. I've got it. For those who are in the same boat, the step-by-step answer is below:
A lot of problems other users were encountering could be solved by having permissions for internet turned on in the manifest, but mine was a little more complicated. Turns out, the main trick is to not include ftp:// in the address in Java.* Also, when you are entering an FTP site, make sure you enter via the root page, so my original page of ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt becomes: ftp.nasdaqtrader.com.
Make sure to download and include the right Apache Commons library in your project (here: http://commons.apache.org/proper/commons-net/download_net.cgi).
Connect to the root page:
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp.nasdaqtrader.com");
Login anonymously, in this case, both username and password are "anonymous". This might be the case with many FTP pages, but I can't be sure:
ftpClient.login("anonymous", "anonymous");
Then, go to the correct directory (be careful about including/excluding the slashes):
ftpClient.changeWorkingDirectory("/SymbolDirectory");
Finally! You can now get the InputStream from the posted text file:
InputStream is = new BufferedInputStream(ftpClient.retrieveFileStream("nasdaqlisted.txt"));
Then, convert the InputStream into String and manipulate as needed. There are many ways to do this. One of which can be found here: How can I convert InputStream data to String in Android SOAP Webservices
*Source: Android FTP connection Failed
If you get "425 Unable to build data connection: Connection timed out" error, then after connecting to ftp server, I would recommend you to set the local mode to passive mode by the following statement.
ftpClient.enterLocalPassiveMode();
I want my program to have a pop-up save as window option before file start downloading, however when I run my servlet it automatically starts downloading the file. What am I missing here ?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fis=new FileInputStream("E:/sound.mp3");
response.setContentLength(fis.available());
response.setContentType("audio/basic");
response.addHeader("content-disposition", "attachment;filename=abc.mp3");
while(true){
int read = fis.read();
if(read==-1)break;
outputStream.write(read);
}
fis.close();
}
Your program is NOT desktop/standalone, since it is a servlet running on a server. When you run it in Eclipse by right clicking and run as -> run on server, Eclipse actually opens a web page to display the results. Therefore, your program is now a Web application, and Eclipse (or the page it opens) is the client. The client is saving the information you sent, NOT your program. Got it?
The content-disposition header is there only to suggest the file name of the download. The browser settings define if it will open a Save As Window or not. You cannot control that.
For example, in Google Chrome, in Setting/Advanced Setting/Downloads, there is the option Ask where to save each file before downloading. Only if this option is selected it will open the dialog you want. Otherwise it will save it in a default location (also defined in the browser settings). Similar options exist for all browsers.
Please also note that, depending on the content-type header, the browser will try to display the content, and not download it. For example, the browser will try to display texts and html. But then you can force the download by setting the header to a non-displayable type:
response.setContentType("application/octet-stream");
In case you don't want to create a Web app: Since your program runs on a server, it simply sends the information and is done. It is the client program who decides what to do with it. In your present case the client is a browser (or Eclipse opening a browser page). Headers such as the content-disposition header are aimed at browsers. If you are to create your own client (Swing client, Android app, iPhone app) which is NOT a browser, then the client will receive the information from the server and decide what to do with it (display it, or save it in any way), even ignoring the HTTP headers.
Try looking here: http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm
take out the main statement in their code and put run(new FileChooserTest(), 250, 110); in your own code. If I were doing it, I would make an int named saveStatus and 3 finals that equal 0, 1, and 2 named waiting, save, and cancel. Then I would do a while loop in your other programming to see if saveStatus was equal to waiting to pause your program (but not the dialog). Afterwards, I would make an if statement to see if saveStatus was equal to save. If so, download it, and if not, don't. Simple as that.
Your problem is the Mime-Type. Some types (especially those where a specific handler is known) will be downloaded directly by most browsers. It does help a bit to use application/binary, but even then some browsers might be configured to download it or interpret the file name extension in the disposition handler.
I think most solutions use javascript on the page before the download link.
You have to implement the dialog manually, e.g. (http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html). After user selecting the file, you will be able to start the http request download (to your servlet) and save the file to the desired path.
I have an applet which is partly designed to (only) read in text files and make stuff based on that. in my applet, this is what I have as the "read" method which reads in files:
public void read (String file1) throws IOException
{
str.removeAllElements (); // str is a global vector
BufferedReader dia = new BufferedReader (new FileReader (file1));
for (;;)
{
strc = dia.readLine ();
if (strc == null)
break;
str.add (strc);
}
}
this works fine when I'm running it through the JVM, but when I take it online the files that I want to access are not accessible even though they are hosted on the same server and folder.
HTML for my applet looks like this:
<applet
codebase = "[the url that hosts my class and text files]"
code = "[my class file].class"
width = ###
height = ###>
</applet>
The specific error I'm getting is:
AccessControlException
access denied ("java.io.FilePermission" "dial1.txt" "read")
So if anyone could help, that would be awesome!
I suspect the real problem here is using a java.io.File. Put server/client aside for the moment and a sand-boxed applet cannot establish a File - at all. But to extend that slightly, a trusted applet can establish a File - but only one that points to files on the local drives of the client machine. A File can never point back to the server, they just don't work that way.
So that leads to. The proper way for an applet to access resources is by URL. Java uses URLs a great deal, even for accessing classes in Jars.
A sand-boxed applet can establish an URL pointing back to the server from which it was deployed.
As to how to form that URL. The URL can be formed relative to the code base (the location of the Jars/classes) or document base (the location of the HTML).
Applets run inside the web browser. Hence, on the computer of the user who downloads your applet. So even if the files you are looking for exist on the computer of the user you won't be able to read them because you don't have file system access to people surfing the internet. Read your local file on server-side. So in your case, you probably need a servlet instead of an applet.
I was expecting this code to return a 404, however it produces the output :
"Response code is 200"
Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,
try
{
// create the HttpURLConnection
URL url = new URL("http://www.thisurldoesnotexist");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + connection.getResponseCode());
}
EDIT: I see you've call openConnection() but not connect() - could that be the problem? I would expect getResponseCode() to actually make the request if it hasn't already, but it's worth just trying that...
That suggests you've possible got some DNS resolver which redirects to a "helper" (spam) page, or something like that.
The easiest way to see exactly what's going on here is to use Wireshark - have that up and capturing traffic (HTTP-only, to make life easier) and then run your code. You should be able to see what's going on that way.
Note that I wouldn't have expected a 404 - because that would involve being able to find a web server to talk to to start with. If you're trying to go to a host which doesn't involve, there shouldn't be an HTTP response at all. I'd expect connect() to throw an exception.
try adding a "connection.connect();" or look at the contents returned...
it could be a dns issue, ie: your dns is being sent to a parking place... for example: freedns does this.
You could:
Resolve the IP from the host of the page
Try to connect to port 80 on the resolved IP using plain sockets
This is a bit low level however and will add complexity since you will need to make a simple GET request through the socket. Then validate the response so you're sure that its actually a HTTP server running on port 80.
NMap might be able to help you here.
Ideally you should be getting this error:
java.net.UnknownHostException: www.thisurldoesnotexist
But it looks like your URL is resolved by you DNS provider.
For instance on my company's network running your code with URI "http://profile/" displays
the employee profile.
Please also check etc.home file if you are on windows to check if any settings have been changed.
Like #spgennard - I think this is most likely a DNS issue.
The URL you have chosen is owned by a DNS speculator.
The URL you have chosen is "parked" by a DNS provider.
Your ISP is messing with your DNS results to send your browser to some search page.
It is also possible that you are accessing the web via a proxy, and the proxy is doing something strange.
The way to diagnose this is to look at the other information in the HTTP responses you are getting, particularly the response body.
I've had to update a previous java application that requests a SOAP response from an external web service. This service is outside our firewall which now requires us to go through a proxy instead of hitting the URL directly.
Currently the Java App uses URLEndpoint that takes a string for the URL. Usually when I am getting to a URL through a proxy I create a URL like so:
URL url = new URL("http", "theproxy.com", 5555, finalUrl);
The problem is URLEndpoint only takes a string for the url, I tried to convert URL to string using toExternalForm() but it malformed the URL.
Any ideas as to a way around this?
EDIT: I can't use System.setProperty as this runs with a whole heap of other Java applications in tomcat.
second edit: I can't set a system properties as it will override all other applications running on the server, I can't use jsocks as the proxy we run through squid proxy which does not support socks4/5
Any help appreciated.
That's not how proxy's work. The way a proxy works is that you take your normal URL:
http://example.com/service
and instead of looking up "example.com" and port 80, the message is sent to your proxy host instead (http://theproxy.com:5555).
Java has built in proxy handling using http.proxyHost and http.proxyPort System properties.
So in your case you would need to do:
System.setProperty("http.proxyHost", "theproxy.com");
System.setProperty("http.proxyPort", "5555");
Then your code should, ideally, "Just Work".
Here is a page documenting the proxy properties.
Use Apache HttpClient and do as show in this example.
About the URL constructor with individual proxy setting:
http://edn.embarcadero.com/article/29783
(sorry don't have privileges to comment)