URLConnection in applet

I'm having an applet communication problem... here is the scenario:
A user can click on an area on the applet. This initiates a URLConnection to the server. The server sends back a response and the applet deals with it.
Sometimes, if a user clicks on the applet once and then again (maybe 1 second later), the applet freezes up as if its waiting for the server to send a response back. After about 5 minutes, it finally clears and the applet is now responsive again. However, each click of the mouse now results in the same freezing problem every time. This only happens with IE (5.5) ... I haven't been able to reproduce the same thing in Netscape (4.7). There are no error messages or exceptions thrown either on the client or server.
If anyone has any ideas or suggestions, I would appreciate any advice.
Thank you.

I've had this problem for a while. I didn't realise that it was specific to
IE 5.5 though. The last time I posted I didn't get any replies that helped
solve the problem. What I've had to do is prevent the user from clicking
on the applet while I'm waiting for the response to the first click. It's not
a very satisfactory solution but I needed some workaround quickly.
I couldn't find a way to consume the user's mouseclick events (because
you don't have access to the System event queue from an applet) and disabling
the component didn't work so I eventually calculated the time difference between
the last response from the server and the current user's click. If it's less than
2ms then I ignore it, otherwise I carry on as normal.
If you come up with a proper solution, please let me know.
Alan

Similar Messages

  • URLConnection and applet security

    Hello,
    I've got an applet that comunicates with a servlet with a urlConnection object. If I test de application without permissions of security (Applet Viewer ->Eclipse), the program runs perfectly, but when I test it in the server throws a security exception when the URLConnection connects with the servlet? How can I resolve it?
    Thanks

    The first part works ok, but in the two try-catch show me the error-messages.
    urlServlet = new URL(new URL("http://85.59.55.122:8080/utilidades/"),"imagen");
    URLConnection con = urlServlet.openConnection();
         con.setDoInput(true);
                             con.setDoOutput(true);
                             con.setUseCaches(false);
                             con.setRequestProperty(
                                       "Content-Type",
                                  "application/x-java-serialized-object");
         ImagenPerso imagen=new ImagenPerso(img);          
    try{
                             OutputStream outstream = con.getOutputStream();
                             ObjectOutputStream oos = new ObjectOutputStream(outstream);
                             oos.writeObject(imagen);
                             oos.flush();
                             oos.close();
                        }catch(Exception er3){
                             JOptionPane.showMessageDialog( graph,
                             "Error al incrustar objetos en la peticion",
                             "Editor de procedimientos",
                             JOptionPane.ERROR_MESSAGE);
    try{
    //                    receive result from servlet
                             InputStream instr = con.getInputStream();
                             ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
                             String result = (String) inputFromServlet.readObject();
                             inputFromServlet.close();
                             instr.close();
                        }catch(Exception i){
                             JOptionPane.showMessageDialog( graph,
                             "Error al leer objetos de la respuesta",
                             "Editor de procedimientos",
                             JOptionPane.ERROR_MESSAGE);
                        }

  • Urgent: how to run applet which connected to the servlet?

    hi frends:
    i have written an applet on the server side and it supposed to pass parameters to my servlet and retrieve some info from the servlet.
    i put both applet and servlet under tomcat../WEB-INF/classes. but when i run the applet from the web browser, there is no response from the servlet.
    could anyone help me to solve this problem?
    one more thing is i know that applet is able to connect to servlet, but how about java application? is it able to do so? if yes, is it also using URLconnection as applet? and how to run it?
    i will be very appreciate if anyone can help me... thanx a million.

    You can connect to the servlet from an application.There's a URL class in java.net that has an openConnection method. Then cast the return to an HttpURLConnection and use setMethod to set up as a post request.This may be the default if you call setDoOutput(true) on the URLConnection. Then you'll need to get an OutputStream and write properly formatted form POST data to it. It's also possible to encode your data on the URL, even when using the POST method, and this may be easier when doing it programmatically from an application. To send a get request you can append the name-value pair at the end of the url.

  • Losing session ... please help me

    I am developing a program that connect between Applet and Servlet.
    I have a problem that losing session in servlet , when I request a servlet using URLConnection in Applet.
    I don't know why the servlet loses the session.
    I guess that the session is changed when I connect server by URLConnection.
    please give me a hand...

    Try using a java.net.HttpURLConnection instead of java.net.URLConnection. Your session is probably not maintained across requests because cookies aren't being handled properly.

  • How to save image using an image object in servlet on web server

    I'll be very thankful to anyone who helps me in this matter.
    i developed an applet which draws on a buffered image.
    now i want to save this buffered image as a jpg image on the web server.
    i know i have to use servlets or jsp for this.
    but i want to use servlet for specific reasons.
    can anyone plz provide me the code for taking an image object from an applet and saving it thru servlet.
    i need this solution as soon as possible.
    thanks in advance.

    Take a look around for URLConnection, and Applet to Servlet communication (also check the [url http://forum.java.sun.com/forum.jsp?forum=33]Servlet forum).
    Basic concepts will be to open a URLConnection to the URL mapped on your server for the servlet, then send the image, byte by byte, to the servlet, then ask for a reply from the servlet.
    Once asked for a reply the servlet will need to take the image sent to it (hopefully via an HTTP post) and copy it to a location on disk. (You could have a parameter to the request that tells you want to name the file...)
    As for the converting buffered image to JPEG, I haven't done this before, but I know others have. You can look around (more likely to find it in the [url http://forum.java.sun.com/forum.jsp?forum=31]Java Programing[ul] forum) for the code needed.

  • Writing binary data to ASP file from applet through URLConnection

    Hi Everybody,
    I am facing a proble with HttpURLConnection.I want to write some binary data from applet to an ASP file.The other end ASP file read this binary data and process , Here problem is I have opened URLConnection to the page and Created OutputStream and writing byte by Write() method But other end we are not getting bytes...we are not getting error too at java side..can any body help me..do we need to set any property to URLConnection...here I am giving sample code...
    OutputStream os;
    URL uConnect2;
    HttpURLConnection hucConnect2;
    uConnect2= new URL("http://webserver/vnc/sendtoserver.asp?"); hucConnect2=(HttpURLConnection)uConnect2.openConnection();
    hucConnect2.setDoOutput(true);
    hucConnect2.setRequestMethod("POST")
    os=new DataOutputStream(hucConnect2.getOutputStream());
    os.writeBytes("Hello");
    Thanks in Advance
    Madhav

    Do you remember to flush() and close() the stream?

  • How can I use URLConnection to use applet communication with servlet?

    I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
    ====================the applet code below=========================
    import java.io.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.net.*;
    //I have tested that in applet get data from servlet is OK!
    //Still I will change to test in applet post data to a servlet.
    public class TestDataStreamApplet extends Applet
    String response;
    String baseurl;
    double percentUsed;
    String total;
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    private String encodedValue(String rawValue)
         return(URLEncoder.encode(rawValue));
    =========================The servlet code below=====================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class DataStreamEcho extends HttpServlet
    {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          res.setContentType("text/plain");
          PrintWriter out = res.getWriter();
          Runtime rt = Runtime.getRuntime();
          out.println(rt.freeMemory());
          out.println(rt.totalMemory());
          response.setContentType("text/html; charset=GBK");     
          request.setCharacterEncoding("GBK");
          PrintWriter out = response.getWriter();
          HttpSession session=request.getSession();
          ServletContext application=this.getServletContext();
          String currenturl=(String)session.getAttribute("currenturl");
          out.print(currenturl);
    =============================================================
    I have done up,but I found the program don't run as I have thought.
    Can you help me to find where is wrong?Very thank!

    You are trying to pass the current URL to the servlet
    from the applet, right?
    Well, what I put was correct. Your servlet code is
    trying to read some information from session data.
    request.getInputStream() is not the IP address of
    anything...see
    http://java.sun.com/products/servlet/2.2/javadoc/javax
    servlet/ServletRequest.html#getInputStream()
    Please read
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
    .htmlNo,you all don't understand I.
    I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
    All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
    for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
    Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
    =======================applet=============================
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    con.connect();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    =======================servlet=============================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         response.setContentType("text/html; charset=GBK");
    //request.setCharacterEncoding("GBK");
    PrintWriter out = response.getWriter();
    HttpSession session=request.getSession();
    ServletContext application=this.getServletContext();
    //String currenturl=(String)session.getAttribute("currenturl");
    String currenturl=(String)request.getParameter("currenturl");
    out.print(currenturl);
    File fileName=new File("c:\\noname.txt");
    fileName.createNewFile();
    FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
    //applet to a file for a test.
    byte[] b=currenturl.getBytes();
    f.write(b);
    f.close();
    }

  • Applets, URLConnection, IPv6, and Cookies

    The web application I'm working on does part of its cookie authentication by comparing the REMOTE_ADDR header to your cookie, which works fine for browser interaction. But we have a few applets that communicate directly with the server. In mixed IPv4/IPv6 environments, the browser (naturally) communicates using IPv6, but the Applets use IPv4 by default, causing the REMOTE_ADDR comparison to fail (the server expects an IPv6 address).
    I've had mixed results with setting java.net.preferIPv6Addresses to TRUE in my Java settings. This appears to work on my machine, but not on my QA's machine.
    I also tried setting this property programmatically and then signing the applet, but that didn't appear to work at all.
    The alternative I came up with was to find an IPv6 address via InetAddress.getAllByName(host), and use that for my URL instead of the hostname. This reports the correct IP address in REMOTE_ADDR, but since I'm not using the same name as in the browser, my browser cookies don't come along for the ride. I've tried getting the cookies by opening a connection to the correct hostname and reading connection.getRequestProperties() or connection.getHeaderField("Set-Cookie"), but I don't get any information back.
    Does anyone have any ideas as to how I can either
    a) Force the applet to connect using the correct IP stack, or
    b) Grab the cookie from the browser
    Thanks.

    try
    URLConnection.setUseCaches(false)
    setUseCaches
    public void setUseCaches(boolean usecaches)
    Sets the value of the useCaches field of this URLConnection to the specified value.
    Some protocols do caching of documents. Occasionally, it is important to be able to "tunnel through" and ignore the caches
    (e.g., the "reload" button in a browser). If the UseCaches flag on a connection is true, the connection is allowed to use
    whatever caches it can. If false, caches are to be ignored. The default value comes from DefaultUseCaches, which defaults to
    true.
    or try to delete old cookies by calling Cookie.setMaxAge(0)
    in your jsp

  • URLConnection.getOutputStream() hang when applet displayed a second time

    This is happening on Linux using the 1.31_02 plugin.
    My applet uses a URLConnection object to get information from a servlet. This method is in it's own thread, and is periodically called to keep the display of the applet up to date.
    The second time the applet is displayed (navigate away from the page and then return), the applet hangs in the method URLConnection.getOutputStream().
    Note that this only happens on Linux browsers, it's fine on Windows.
    Is there any way to programatically force a reset on the URL? The only way I have been able to recover is to restart the browser.
    Thanks.

    I am having similar problem with URLConnection.getOutputStream() that hangs in Mozilla 1.2.1 browser when it tries to write to linux server. It never creates this object outputStream = new BufferedWriter( new OutputStreamWriter(connect.getOutputStream())); System.out.println before this line shows but the one after does not show at all. Can you help? I am using Java plug-in 1.3.1_02. I would appreciate any help.

  • Bypassing proxy/firewall with Applet URLConnection?

    I am trying to download images from an image server to an Applet. Currently I am using URLConnection to connect to server and download the image to a byte array.
    The problem arises when I try to download the images through a proxy/firewall. The applet doesnt seem to connect to the server using URLConnection, however it works fine over a standard modem connection!
    Running the code as an application, instead of an applet with the following parameters to use the proxy :
    Properties systemProperties = System.getProperties();
    systemProperties.put("proxySet","true");
    systemProperties.put("proxyHost",host);
    systemProperties.put("proxyPort",proxyport);
    System.setProperties(systemProperties);
    This works perfectly, and the images are downloaded.
    The problem is that I need to run it as an applet and not as an application. I was under the impression that the browser settings for proxy and port will automatically be sent to the applet and I dont have to set it manually.
    Please let me know if anyone has any solutions. Thanking you in anticipation!

    On IE, you can to limit the addresses that will go to access the proxy server.
    On Tools Menu select the "Internet Options" Then "Connections" then "Lan Configurations" Then "Advanced" then "Exceptions" now input the addresses that don�t will utilize the proxy/firewall.
    Excuse-me by my English.
    Best Regards
    Isaias Cristiano Barroso
    [email protected]

  • Applet URLConnection to servlet

    in an applet i open an ObjectOutputStream to a Servlet over a URLConnection - then i write something - then i close the stream.
    then i am trying to open an ObjectInputStream over the same URLConnection an i get an IOException.
    thx in advance!

    two URLConnections and everything ok...

  • Applet using  URLConnection.setUseCaches (true) cause OutOfMemoryError

    Hi all,
    I had this prloblem for a couple of weeks.
    We had a applet app that retrieve images and show on applet pages. On the applet page there are some image icon like print, rotation, copy ... on the sidebar, also I have two jar files including those classes and images on sever. When users access the applet page, the applet image (a document) show up immediately, but the button icon loading very slow one by one. From java console I can see one jar file which contain image icons were loaded multiple times and very slow about 8 to 10 minuts, after complete loaded, retrieve others will be fine.
    I think the cache set to false cause that.
                   urlConnection.setUseCaches (*false*);
                   urlConnection.setDefaultUseCaches (*false*);But if I set to true:
                   urlConnection.setUseCaches (*true*);
                   urlConnection.setDefaultUseCaches (*true*);My understanding is that allow to loading very image into local cache. After user retrieve images (about 30 times, they clicked on a document icon to show the image) for certain times, the browser frozen and java console show a error:
    com.ibm.mm.viewer.CMBDocumentEngineException: Java heap space
    java.lang.OutOfMemoryError: Java heap space
    I tried jre1.4.2, 1.5 and 1.6.0_02/_06/_10, didn't work!
    jre1.4.1 was fine but our user will use jre1.5 or higher.
    Anybody has a solution?
    Many thanks!!!
    Jx
    Edited by: cooooooooool on Nov 25, 2008 7:19 AM

    Ah, turns out I had to read the input too. Though I didn't produce much output myself in the script ;)

  • How to  � applet URLConnection � to the same HttpServlet session.

    Hi my applet needs to upload some data to be appended to previous uploads every few minutes.
    I tried with
    session = request.getSession (true);
    sessionId = session.getId ()
    pass sessionId to applet and
    On the applet side
    URL url = new URL (serverURL +"?JSESSIONID="+sessionId);
    or
    URL url = new URL (serverURL +�?�+sessionId);
    It is not working
    Any help is appreciated.

    Hi tolmank,
    I tried
    URL url = new URL (serverURL +":JSESSIONID="+sessionId);
    I get
    java.io.FileNotFoundException: http://localhost:8084/RACServer12/RACServlet:JSESSIONID=534E1D0B183BC12CEB36EBB8371720CF
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1131)
    at client.UpLoadThread$1.run(UpLoadThread.java:76)
    at java.lang.Thread.run(Thread.java:595)
    Can�t find the session
    Then I tried
    URL url = new URL (serverURL +";JSESSIONID="+sessionId);
    Can�t find the session
    Then I tried
    Applet side.
    con.setRequestProperty("Cookie", sessionId);
    Can�t find the session.
    Any help is appreciated.

  • Applet URLConnection.getInputStream() blocks

    There seems to be a bug in Java (#4333920, #4976917) that causes the getInputStream() method to
    block and never return. I've tried many things to solve this. I'm using Java 1.4 to connect to servlet
    running on Tomcat. Does anyone know a solution to this problem?

    Nevermind. I found the problem, which was at the client side I wasn't closing the url connection before opening a new one. After I added the line
    HttpURLConnection con = ...;
    con.disconnect();
    The getInputStream() never blocked.

  • Applet java file not refreshing in browser

    I have an applet that I am updating and I am not seeing the corresponding update when I open the web page. I can manually download the java class file and look inside it and it definitely is the updated file. I have deleted the browser history. (I am running tests with Firefox 3, IE7, and Safari 4 public beta). Is there something else I need to do to make sure the browser pulls in the latest version of the class file referenced in the html?
    Here is the code:
    <HTML>
    <HEAD>
       <TITLE>A Simple Program</TITLE>
    </HEAD>
    <BODY>
       <CENTER>
          <APPLET CODE="SendRequest.class" WIDTH="500" HEIGHT="150">
          </APPLET>
       </CENTER>
    </BODY>
    </HTML>The applet refers to a hard coded URL to read through a urlconnection. It is always reading a file and showing content, but it is not showing the right file. If I change the name of the referenced file in the java program, it looks like the browser has cached the referred file, rather than throwing and error and saying the file doesn't exist.
    Here is the java
    import java.applet.*;
    import java.awt.*;
    import java.net.URLConnection;
    import java.net.URL;
    import org.w3c.dom.Document;
    import java.lang.String;
    import java.io.*;
    public class SendRequest extends Applet {
        @Override
        public void paint(Graphics g) {
            g.drawRect(0, 0, 499, 149);
            g.drawString(getResponseText(), 5, 70);
        public String getResponseText() {
            try {
                URL url = new URL("http://myserver.com/stats/logs/ex20090603000001-72.167.131.217.log");
                URLConnection urlconn = url.openConnection();
                BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    urlconn.getInputStream()));
                String inputLine;
                String htmlFile = "";
                try {
                    while ((inputLine = in.readLine()) != null)
                        htmlFile += inputLine;
                    in.close();
                    return htmlFile;
                } catch (Exception e) {
                    return "Can't get the string.";
            } catch (Exception e) {
                return "Problem accessing the response text.";
    }Any help would be appreciated. I heard that some files may cache more persistently than others, but I don't fully understand the details.
    Thanks,
    Jim

    Check this [document loader example|http://pscode.org/test/docload/] & follow the link to sandbox.html for tips on clearing the class cache. That relates specifically to caching a refused security certificate, but class caching is much the same. As an aside, getting a console can be tricky in modern times (unless the applet fails completely). It is handy to configure the [Java Control Panel|http://java.sun.com/docs/books/tutorial/information/player.jnlp] to pop the Java console on finding an applet (Advanced tab - Settings/Java Console/Show Console).
    Of course there are two better tools for testing applets, especially in regard to class caching. AppletViewer and Appleteer both make class refresh fairly easy. Appleteer is the better of the two. I can tell you that with confidence, since I wrote it. ;-)

Maybe you are looking for

  • ITunes moves music up one level after play

    Hi All: iTunes recently started moving played music up a folder level once played.  I have iTunes 10.4.1 on a Windows 7 machine, and it is set to organize my music. Normally, music is kept in the subfolder Music in my iTunes library folder, but the M

  • Is there a way to sort songs into alphabetical order under artist as opposed to being grouped by album?

    Hi all. After a long overdue update to my ipod touch I've noticed that when I select an artist my songs are now grouped by album as opposed to alphabetically. Wondering if its possible to change this as I cant find any options or information on this

  • No sound in APP CS3

    Hello! I've got a problem with Adobe Premiere Pro CS3. I bought new camera Praktica DVC 10.4 HDMI. When I import film to the program, there is no sound on the timeline. The same happens with After Effects CS3. In Windows Movie Maker and the other pro

  • Deleted adapter will still recieve messages from the hub

    Hi! Short - some background: We were to move our application from one database to another, and for backup-reasons, we chose to create a new adapter for the new database. I created an adapter which I made subscribe to a few events. I started the adapt

  • When is the best time to charge an iPod for optimal battery?

    What do you think? I hear if you let it go all the way down and then recharge it meaning full discharge then recharge, it's bad for the battery overall. Also I hear it's bad to charge it constantly as it would make the battery weaker as well? So when