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.

Similar Messages

  • InputStream in = urlconnection.getInputStream();

    Dear All,
    I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
    In the client program, after opening all the necessary streams and all formalities, i am using the code...
    "InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1);"
    only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
    so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
    what to do???
    any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
    sakthivel s.
    snippet code for ur reference...
    Client side
    try
    ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
    ZipEntry zipentry = new ZipEntry(filename);
    zipentry.setMethod(ZipEntry.DEFLATED);
    zipoutputstream.putNextEntry(zipentry);
    byte bytearray[] = new byte[1024];
    File file = new File(filenamedir);
    FileInputStream fileinputstream = new FileInputStream(file);
    BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
    int length = 0;
    while((length=bufferedinputstream.read(bytearray)) != -1)
    zipoutputstream.write(bytearray,0,length);
    fileinputstream.close();
    bufferedinputstream.close();
    zipoutputstream.flush();
    zipoutputstream.finish();
    zipoutputstream.closeEntry();
    zipoutputstream.close();
    InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1); // the said while loop....................
    System.runFinalization();
    urlconnection.getInputStream().close();
    urlconnection.disconnect();
    the way of connecting witht the server : (just a snippet of the code)
    URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
    HttpURLConnection.setFollowRedirects(true);
    urlconnection= (HttpURLConnection)serverURL.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setRequestMethod("POST");
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    urlconnection.setUseCaches(false);
    urlconnection.setAllowUserInteraction(true);
    urlconnection.setRequestProperty("Cookie",cookie);
    urlconnection.connect();
    Server Side:
    javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
    ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
    ZipEntry zipentry = null;
    String directory="c:\\test"; // the unzipped file should be written to this directory...
    try
    File file = new File(directory);
    if(!file.exists())
    file.mkdirs();
    catch(Exception exp)
    {System.out.println("I am from Server: " + exp);}
    try
    zipentry = zipinputstream.getNextEntry();
    if(zipentry != null)
    int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
    String filename = zipentry.getName().substring(slash);
    File file1 = new File(directory + File.separator + filename);
    FileOutputStream fostream = new FileOutputStream(file1);
    BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
    byte abyte0[] = new byte[1024];
    for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
    bufferedoutputstream.write(abyte0, 0, index);
    servletinputstream.close();
    bufferedoutputstream.flush();
    bufferedoutputstream.close();
    zipinputstream.closeEntry();
    zipinputstream.close();
    fostream.flush();
    fostream.close();
    catch(IOException ioexception)
    {System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
    P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

    snoopybad77 wrote:
    I can't, I'm using java.net.URL and java.net.URLConnection....Actually you are using HttpURLConnection.
    java.net.URLConnection is an abstract class. The concrete implementation returned by openConnection for an HTTP based URL is HttpURLConnection. So you might want to try the previous suggestion and otherwise examining the methods of HttpURLConnection to see how they might be helpful to you.

  • Bad Record MAC. exception while using urlConnection.getInputStream()

    All,
    In my SAP J2EE instance, from filter I am trying to do get data from an url (protocol is https).
    For this I am using urlInstance.openConnection() after that urlConnection.getInputStream() and then reading from this input stream.
    When I use http protocol, everything works fine. But with https, during urlConnection.getInputStream(), I get an exception saying "Bad Record MAC".
    I tried to execute the same code in a standalone java program. It went fine with both http and https.
    I get this error only when I run in SAP J2EE instance and only with https.
    From the exception trace, I can see that while running in J2ee engine, the URLConnection instance is org.w3c.www.protocol.http.HttpURLConnection.
    When I run a standalone program from command prompt, the instance is com.ibm.net.ssl.www.protocol.https.r. This runs without any issues.
    I understand that these instances are different due to different URLStreamHandlerFactory instances.
    But I didnt set the factory instance in either of the programs.
    1. Is the exception I get is simply bcoz of instance org.w3c.www.protocol.http.HttpURLConnection?
    2. In that case how can I change the factory instance in j2ee engine?
    Please help.
    Thanks.
    Edited by: Who-Am-I on Nov 28, 2009 7:54 AM

    May be my question is too complex to understand. Let me put it simple.
    After upgrading to NW 7.01 SP5, an existing communication between SAP J2EE engine and a 3rd party software is not working.
    After a lot of debuggin I came to know that its happening at the filter we implemented to route the requests through the 3rd party authentication system.
    At the filter exception is coming from org.w3c.www.protocol.http.HttpURLConnection.getInputStream.
    This instance of HTTPURLConnection given by protocol handler factory(implementation of URLStreamHandlerFactory) which SAP is considering by default. I want to replace this protocol handler with another handler as I see no problems running the same program outside SAP J2EE instance.
    Can we change this protocol handler factory? Where can we change it?

  • Re: Cannot get new URLconnection.getInputStream() in JAVA

    new URLConnection.getInputStream() does not seem to work.
    Background: I am trying to POST the data to an ASP page and reading the response back but it does not seem to work...if I comment this line out it works but does not do what it is intended for.
    Basically I am trying to upload files to the server and am connecting to the URL and writing to its stream....but cannot read the response back..Please help as I have tried everything I could and have read the forums but no LUCK yet

    Yeah yeah that is what I meant ...please excuse me for that ... jst getting slightly pissed off with this problem....see the code below...
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    this is where the error is coming from and the server throws error no 500.
    I have tried posting to the same URL using a Form and it works without any issues....please help

  • URLConnection.getInputStream()  not reading the full HTML

    I need code to read a html file after posting a request. The code is as follows:
    URLConnection connection = url.openConnection();
    connection.setDoInput( true );
    connection.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    if(in.equals(null)){
    throw new IOException();
    while((inputLine = in.readLine()) != null){
    System.out.println("line is: " + inputLine);
    Sometimes it works fine. Sometimes it can not read full content.(may be the low network). but i view the source in my browser, I can find it just fine.
    Any ideas? Has anyone encountered this kind of problem?

    my code is same for reading input from a servlet, but it sometimes get and inputstream, sometimes, don't, it always can not read the second one. mine code is inside applet and chat with other applet thourgh a servlet. The server side does write message out.
    Any insight how to debug this, I am totally out!!

  • URLConnection getInputStream()

    Hi guys.
    I am writing an applet that is getting information from a .php file. I am opening a connection to the .php and posting to it, then I am opening an input stream from the connection and reading from it.
    From the input stream, I can easily open a stream reader and read the data from it, but when I try to pass the input stream to another function, the program stalls indefinitely.
    Here is an example:
                   //works fine
                                    URLConnection conCon = conURL.openConnection();
                        conCon.setDoOutput(true);
                        conCon.setUseCaches(false);
                        OutputStreamWriter conOut = new OutputStreamWriter(conCon.getOutputStream());
                        conOut.write(conPost);
                        conOut.flush();
                        conOut.close();
                        InputStream conIS = conCon.getInputStream();
                        BufferedReader buff = new BufferedReader(new InputStreamReader(conIS));
                        System.out.println(buff.readLine());
                    //but if instead I do
                        InputStream conIS = conCon.getInputStream();
                        conSeq = FastaParser.getSequence(conIS);
    //elsewhere
         public static String getSequence(InputStream is) throws IOException{
              String seq = "";
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              String line = br.readLine();
                    return line;
    //it times outThis is just an example. I am doing other things with the input stream. Is there any way to stop it from stalling here?
    Edited by: shiroganeookami on Oct 19, 2007 9:21 AM

    shiroganeookami wrote:
    well, here's the actual code:
    ...I don't see anything in that which would behave badly, other than possibly not checking your initially read string for null or checking string lengths before trying to use charAt(0) on it. I do see that you're conditionally building a "seq" string and then tossing it, returning only the last line (or null) you read, so that doesn't look right. But it doesn't look like it could possibly be the problem leading to this topic.
    Looks like you better do some (more) debugging, by running in a debugger if possible, or at a minimum logging clues along the way, such as putting a
    System.out.println("Here's the line I just read from the stream:" + line + ":");
    in the do-while loop to see if it's getting in there and what you're reading from the stream.
    And log other clues as well, such as at the end of the method to let yourself know whether the method returned or not, and before and after each br.readLine to let yourself know whether the readLine is hanging.

  • 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

  • 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]

  • Getting images using URLConnection.getInputStream

    Hi,
    I'm trying to get an image with the following code but the image is garbled. Does anyone know what I'm missing?
    try
    PrintWriter out =response.getWriter();
    String userUrl= "http://freshmeat.net/img/url_changelog.gif"
    int buffer=4096;
    byte[] stream = new byte[buffer];
    int input=0;
    URL url = new URL(userUrl);
    URLConnection conn = url.openConnection();
    String contentType=conn.getHeaderField("Content-Type").toUpperCase();
    if(!contentType.equals("TEXT/HTML"))
    response.setContentType(contentType.toLowerCase());
    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
    while((input = in.read(stream, 0, buffer)) >=0 )
    out.write(new String(stream).toCharArray());
    in.close();
    in=null;
    out.flush();
    out.close();
    Thanks,
    Ralph

    It's not what you are missing, it's what you have extra. You are converting the stream of bytes to a String. That is what garbles your image. Don't do that. Instead, doOutputStream out = response.getOutputStream();and copy the bytes to it, using basically the same code you are using now.

  • 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.

  • URLConnection.getInputStream() craches thread

    Hi
    I'm trying to parallelize a downloading process i'm developing, and my download started to behave a bit sporadic. The thread dies right after the System.out.println("1") in the following code snippet, s is an url.
    for(String s:urls) {
      try {
        URL url = new URL(s);
        URLConnection uc = url.openConnection();
        System.out.println("1 " + s);
        InputStream is = uc.getInputStream();
        System.out.println("2");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));the output from strace (list of system commands) on my system shows the following relevant part:
    [pid  4438] write(1, "1 http://alatest1-cnet.com.com/4"..., 513 http://alatest1-cnet.com.com/4941-3000_9-0-1.html) = 51
    [pid  4438] write(1, "\n", 1
    ) = 1
    [pid  4438] gettimeofday({1174556453, 323179}, NULL) = 0
    [pid  4438] send(17, "GET /4941-3000_9-0-1.html HTTP/1"..., 177, 0) = 177
    [pid  4438] recv(17, <unfinished ...>
    [pid  4438] <... recv resumed> 0xb52e6cb0, 8192, 0) = ? ERESTARTSYS (To be restarted)
    this is the last output from this pid, it seems like it just lies down and dies efter it got the ERESTARTSYS.
    I have tried this on java 1.6.0 and 1.5.0_07 with linux kernel 2.6.17.7.
    Am I calling the connecting function wrong, or is there some other error maybe?

    sorry to be a little unclear.
    I don't get any exceptions, and i also added a catch(Exception e) { System.out.println(e); } to make sure.
    The Thread doesn't hang, it just dies silently.

  • URLConnection.getInputStream and synchronization.

    I can't quite understand why url.getInputStream must by globaly synchronized, if it isn't I will start to receive "connection refused" exceptions
    import java.net.*;
    import java.io.*;
    public class TestURL {
        private final Object lock = new Object();
        public void test() {
            for(int i=0;i<1000;i++) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            while(true) {
                               URLConnection url = null;
                               url = new URL("http://localhost:5222").openConnection();
                               InputStream s;
                               synchronized(TestURL.this.lock) {
                                   s = url.getInputStream();
                               while(s.read() != -1) {};                            
                               s.close();
                               System.out.println(Thread.currentThread().hashCode());
                        }catch(Exception e) {
                            e.printStackTrace();
                }).start();
                System.out.println(i);
            while(true);
    }

    moonlighting wrote:
    Hmmm, I don't quite understand your answer could you be more specific ?Without the synchronization you create and start 1000 threads with each one accessing the same URL. Can the server cope with 1000 requests at pretty much the same time?
    With the synchronization, each thread has to acquire a lock on the object referenced by 'TestURL.this.lock' so only one can run at a time. All the other 999 will be suspended until they can acquire the lock.

  • 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...

  • Process.getInputStream() block after some time

    Hello!
    First sorry for my bad english. I have a problem. I hope anybody can help me!
    I have this source snipplet
    this.Main.ffmpeg = runtime.exec(cmd);
    this.is = this.Main.ffmpeg.getInputStream();
    while(true) {
         d = this.is.read();
         if(d == -1) {
              //End of file
    }The subprocess is ffmpeg with piped output (binary data)
    After some time, in this case about 10-15 minutes, the read() function blocks running. I dont understand why, because ffmpeg is still running (not running because it is waiting for output read).
    Can anybody help, why read blocks my loop, and why not read more data?
    Thanks!

    I made some test.
    a.)I run process the same process without my application in a shell: ffmpeg -i ..... - > /dev/null.
    The process hasn't stopped producing output. I tried many times.
    And...
    I tried my java program with "cat /dev/urandom". It hasn't blocked the read() function for a long long time.
    So I think something wrong with binary data (I can't think another thing). Something isn't good for InputStream.
    b.) 'd' is int, but a some lines later I do a cast to byte:
    if (d != -1) {
        this.Main.buffer[this.Main.written_byte++] = (byte) d;
        num++;
    } else {
         break; //from is.read() loop
    }I don't thik this can be problem.
    Maybe I need to read not bigger blocks, with read(Byte[] arg0, int arg1, int arg2)?

  • Network speed check Java applet is "security" blocked

    IHA has been asking for some time to optimize speed.
    Finally had just done a reboot & figured it was a good time to try.
    When you run the Network Diagnostic tool from http://my.verizon.com/services/speedtest/defaultndt.aspx,
    the Java applet JWEB100 comes back as blocked (MSIE, Firefox & Chrome)  A Windows popup (no program attribution) says: 
    Application blocked by Security Settings
    Name: JWeb100
    Location http://nyfiosspeed3.west.verzon.net       [even though I am i NY and it asks for state]
    Your security settings have blocked an untrusted application from running.
    Norton does not really seem to be the culprit, but I could be wrong.  The Java console security setting (midway between medium and high)  seems to indicate a trusted certificate is required, but why would this applet not have a certicate?
    Any ideas?
    Success comes in cans: Failure comes in can'ts.
    Education is what you get from reading the small print; experience is what you get from not reading it. 

    Note works if you authorize the various addresses.  I am not sure if this working as it should or is a work around.
    For Mine I have authorized
    http://my.verizon.com
    http://atlfiosspeed1.west.verizon.net
    http://atlfiosspeed2.west.verizon.net
    http://atlfiosspeed3.west.verizon.net
    http://tpafiosspeed1.west.verizon.net
    http://tpafiosspeed2.west.verizon.net
    http://tpafiosspeed3.west.verizon.net
    The entries besides my.verizon.com depend on where you test against.

Maybe you are looking for

  • Parsing across multiple namespaces... best practice?

    Howdy all, here's my situation: I am attempting to create a simple interface to a particular type of webdav server which has some unusual XML data coming back, and need some advice on the best way to parse this XML. I have a generic "query" object wh

  • Purchase info record numbering

    Hi, I need to create purchase info record for a meterial. for that i have done the following. 1. Created purchase infor record numbering range and group. 2. But at the time of creating the purchase info record the number which displaying is not relat

  • I renewed my subscription, but my old online numbe...

     Really irratated by the fact that I renewed my previous subscription for a online number but my previous online number doesn't show. I think I spent more than I should have on my subscription and it still doesn't do what I thought it would do. What

  • Scaling of Tab-Control do not work correct

    When I use the option "rescale objects on the front panel when resizing" in the "window size" category inside the VI properties, then my tab control has a wrong behavior. When I increase my window size, the tab control increases correctly. When I dec

  • How do i convert songs from itu

    Hi thereA friend of mione has given me some files from itunes and put them on CD for me. However i cant listen ?to them or put them on my creative zen as i need ITUNES to do this. Is there any way to convert them to another format?