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.

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

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

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

  • Error while posting xml file to URL using URLConnection

    Hello everyone,
    I am facing an issue from long time related to URLConnection. If this would be resolved by your help then I would be very grateful to you.
    One application which posts xml file to URL hangs and after waiting for 5 mins it throws 504 error:
    java.io.IOException: Server returned HTTP response code: 504 for URL: http:hostname.
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:715)
    Same application is running fine without error on another environment from last 5 years. But on another env it is erroring out from the day 1.
    We have many workarounds in place none worked.
    I tried to use HttpClient from apache but that too hanged at URLConnection.getInputStream() method call.
    App is running on iPlanet web server 6.1 using JDK 1.4.0_03
    We still dont know why this program hangs at that particular line in only one env but many times it runs fine. That means 30% of the times it posts xml file without error but 70% times it errors out. So our program logic is to retry until post is successful.
    Once this issue is resolved we will remove the logic of trying again and agian.
    Please provide inputs.
    Thanks,
    Nitin

    The HTTP response 504 means that the server, acting as a gateway, has not received a response from an upstream server in the time it expected.
    I think this is problem is due to the remote server that receives the XML and takes too long to return a response to the local application that posted the XML.
    Try HttpClient and set the timeout variable of the HttpClient instance used.
    Here http://svn.apache.org/viewvc/jakarta/commons/proper/httpclient/trunk/src/examples/PostXML.java?revision=480424&view=markup
    a Post XML sample.
    NB: HttpClient > setTimeout method is deprecated. See : http://jakarta.apache.org/commons/httpclient/apidocs/index.html for an alternative
    Hope That Helps

  • URLConnection.read(..) not reading

    Hi all,
    I'm not sure if this is the right place to post this question..
    When i connect to a server (specifically Darwin Streaming Server) with a URLConnection to set up my GET connection, i get nothing back (it blocks) when i try to read from the inputStream even though the server is actually sending back an OK response (which i verified via tethereal).
    On the other hand, if I emulate the same exact thing with a Socket connection, then everything works fine and i can read from the inputStream.
    Any suggestions? (below are the GET request and the OK response)
    Thanks in advance!!
    Sheado
    GET /sample_100kbit.mov HTTP/1.1\r\n
    User-Agent: JMF RTSP Player 1.1\r\n
    x-sessioncookie: 1051045290491\r\n
    Accept: application/x-rtsp-tunnelled\r\n
    Pragma: no-cache\r\n
    Cache-Control: no-cache\r\n
    Host: 192.168.0.168\r\n
    Connection: keep-alive\r\n
    \r\n
    HTTP/1.0 200 OK\r\n
    Server: DSS/4.1.3 (Build/412.45; Platform/Linux)\r\n
    Connection: close\r\n
    Date: Thu, 19 Aug 1982 18:30:00 GMT\r\n
    Cache-Control: no-store\r\n
    Pragma: no-cache\r\n
    Content-Type: application/x-rtsp-tunnelled\r\n
    \r\n

    oops.. i just realized my title is wrong.. i meant UrlConnection.getInputStream().read(..) is not working for me.

  • How can we close a URLConnection ?

    Problem: URL Connections sometimes hang if, socket is there but not responding... the code will hang at urlConnection.getHeaderField(i).
    and My code will keep waiting for infinity ... only solution I have is to close the connection after a specified time (Using a thread).
    Sadly java.net.URLConnection doesn't have close() ...
    Can someone help me on this?
    Regards,
    Neo
    * HostExaminer.java
    * Created on September 28, 2002, 9:47 PM
    package serverconfig.microkernel.examiner;
    import java.net.Authenticator;
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.InputStream;
    import java.util.StringTokenizer;
    import serverconfig.microkernel.request.Request;
    import serverconfig.microkernel.worker.Director;
    import serverconfig.microkernel.worker.Locator;
    import serverconfig.microkernel.worker.Guardian;
    import serverconfig.microkernel.examiner.PresentationObjectInputStream;
    * @author  Neo
    public class HostExaminer implements Examiner {
        /** Creates a new instance of HostExaminer */
        public HostExaminer() {
        public boolean examine(final Request request, PresentationObjectInputStream presentationObjectInputStream){
            Guardian guardian = null;
            synchronized(guardian = Guardian.getInstance(request)){
                Authenticator.setDefault(guardian);
                try{
                    System.out.println("Before URL");
                    final URL url = new URL(new Locator(request).getInstanceURL()+new Director(request).getDirection());
                    System.out.println("Before URLConnection");
                    URLConnection urlConnection = url.openConnection();
                    System.out.println("Before for(;;)");
                    for(int i=0 ; ; i++){
                        System.out.println("Before urlConnection.getHeaderField("+i+");");
                        String header = urlConnection.getHeaderField(i);// <-- here it hangs
                        if(header == null ) break;
                        System.out.println("Before urlConnection.getHeaderFieldKey("+i+");");
                        final String headerKey = urlConnection.getHeaderFieldKey(i);
                        if(headerKey == null){
                            final StringTokenizer stringTokenizer = new StringTokenizer(header," ");
                            stringTokenizer.nextToken();
                            final String token = stringTokenizer.nextToken();
                            request.getResponse().setCode(new Integer(token.trim()));
                        //request.getResponse().appendContent( (headerKey == null ?"": (headerKey + " = ")) + header +"\n" );
                    System.out.println("Before presentationObjectInputStream");
                    presentationObjectInputStream.setInputStream(urlConnection.getInputStream());
                catch(java.net.UnknownHostException uhe){
                    request.getResponse().setCode(new Integer(404));
                    uhe.printStackTrace();
                    return false;
                catch(java.net.ProtocolException pe){
                    request.getResponse().setCode(new Integer(401));
                    pe.printStackTrace();
                    return false;
                catch(java.net.BindException be){
                    request.getResponse().setCode(new Integer(401));
                    be.printStackTrace();
                    return false;
                catch(java.net.ConnectException ce){
                    request.getResponse().setCode(new Integer(503));
                    ce.printStackTrace();
                    return false;
                catch(java.net.NoRouteToHostException nrthe){
                    request.getResponse().setCode(new Integer(408));
                    nrthe.printStackTrace();
                    return false;
                catch(java.io.IOException io){
                    request.getResponse().setCode(new Integer(500));
                    io.printStackTrace();
                    return false;
                catch(java.lang.Throwable th){
                    request.getResponse().setCode(new Integer(500));
                    th.printStackTrace();
                    return false;
            if(request.getResponse().getCode().intValue() >= 400){
                return false;
            else{
                return true;
    }

    HttpURLConnection.disconnect()
    *Sun's Comment:
    * Indicates that other requests to the server are unlikely in the near future.
    * Calling disconnect() should not imply that this HttpURLConnection instance can be reused for other requests.
    public abstract void disconnect(){
    Can you please make me under `what does this comment mean ?`
    Thanx Hedin, HttpURLConnection makes my code neat :) but this method does not close the connection!
    Regards,
    Neo
    * HostExaminer.java
    * Created on September 28, 2002, 9:47 PM
    package serverconfig.microkernel.examiner;
    import java.net.HttpURLConnection;
    import java.net.Authenticator;
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.InputStream;
    import java.util.StringTokenizer;
    import serverconfig.microkernel.request.Request;
    import serverconfig.microkernel.worker.Director;
    import serverconfig.microkernel.worker.Locator;
    import serverconfig.microkernel.worker.Guardian;
    import serverconfig.microkernel.examiner.PresentationObjectInputStream;
    * @author  Neo
    public class HostExaminer implements Examiner {
        HttpURLConnection urlConnection;
        /** Creates a new instance of HostExaminer */
        public HostExaminer() {
        public void disconnect(){
            if(urlConnection != null)
                urlConnection.disconnect();
        public boolean examine(final Request request, PresentationObjectInputStream presentationObjectInputStream){
            Guardian guardian = null;
            synchronized(guardian = Guardian.getInstance(request)){
                Authenticator.setDefault(guardian);
                try{
                    System.out.println("Before URL");
                    final URL url = new URL(new Locator(request).getInstanceURL()+new Director(request).getDirection());
                    System.out.println("Before URLConnection");
                    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                    System.out.println("Before get Response Code");
                    request.getResponse().setCode(new Integer(urlConnection.getResponseCode())); //<<-- It hangs here now !
                    System.out.println("Before presentationObjectInputStream");
                    presentationObjectInputStream.setInputStream(urlConnection.getInputStream());
                catch(java.net.UnknownHostException uhe){
                    request.getResponse().setCode(new Integer(404));
                    uhe.printStackTrace();
                    return false;
                catch(java.net.ProtocolException pe){
                    request.getResponse().setCode(new Integer(401));
                    pe.printStackTrace();
                    return false;
                catch(java.net.BindException be){
                    request.getResponse().setCode(new Integer(401));
                    be.printStackTrace();
                    return false;
                catch(java.net.ConnectException ce){
                    request.getResponse().setCode(new Integer(503));
                    ce.printStackTrace();
                    return false;
                catch(java.net.NoRouteToHostException nrthe){
                    request.getResponse().setCode(new Integer(408));
                    nrthe.printStackTrace();
                    return false;
                catch(java.io.IOException io){
                    request.getResponse().setCode(new Integer(500));
                    io.printStackTrace();
                    return false;
                catch(java.lang.Throwable th){
                    request.getResponse().setCode(new Integer(500));
                    th.printStackTrace();
                    return false;
            if(request.getResponse().getCode().intValue() >= 400){
                return false;
            else{
                return true;

  • If in the URLconnection I setUseCaches(true), I must to wait until...

    Hello, sorry for my english and thanks for all.
    I know how can to use an URLconnection for to get the file size for download and after to get the InputStream read it and to get the progress download.
    If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
    If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
    I have two questions:
    - if I setUseCaches(true), why I must to wait until the file is all download an after I can read the InputStream?
    - how can I get the progress download if setUseCaches(true) in the URLconnection?
    very thanks

    This is the code that I've used:
    try{
         URLConnection urlconnection;
         urlconnection = (new URL(getDocumentBase(), "beni0271.jpg")).openConnection()
         urlconnection.setUseCaches(true);
         //If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
         //If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
         System.out.println(urlconnection);
         length =     urlconnection.getContentLength();
         inps = urlconnection.getInputStream();
         System.out.println(inps);
    }catch(MalformedURLException e){
         System.out.println(e);
    }catch(IOException e){
         System.out.println(e);
    }

  • UrlConnection not getting latest content

    I have an applet that reads the contents of a file on the server once per second and displays it. The file contains one line that describes the status of a process. The problem is there is a 15-20 second delay between when the file is updated and when the applet displays the new status. Here is my applet run() method:
    public void run() {
    Thread currentThread = Thread.currentThread();
    StatusField.setText("Testing");
    String host ="192.168.3.14";
    String protocol ="http";
    int port =80;
    int count = 0;
    BufferedReader bufferedReader = null;
    String stat = "";
    try {
    while (currentThread == theThread) {
    URL url = new URL(protocol, host, port, fileName);
    URLConnection urlConnection = url.openConnection();
    //turn off cache
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput (true);
    bufferedReader = new BufferedReader(new
    InputStreamReader(urlConnection.getInputStream(), "UTF8"));
    stat = bufferedReader.readLine();
    System.out.println("Status: " + stat);
    StatusField.setText(stat);
    bufferedReader.close();
    bufferedReader = null;
    urlConnection = null;
    url = null;
    System.gc();
    currentThread.sleep(1000);
    }catch (Exception e) {
    StatusField.setText(e.getMessage());
    }

    Thanks, but I don't think the problem is with the applet not painting immediately. The System.out.println shows that the BufferedReader is still reading old content even after the file has changed. I also added code to the above to show a dot in the status field every time the file is read. This dot is appearing corectly in the applet every time the file is read.

  • Problem with getInputStream

    Hi,
    I get the following exception in the code -
    java.io.IOException: Server returned HTTP response code: 500 for URL:
    The exception is occurring at URLConnection.getInputStream().
    Could somebody please let me know how to debug this type of exception? What could be the probable cause?
    Any help would be highly appreciated.
    Thanks in advance.

    It would have taken you about 5 seconds to google for http status codes:
    http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    500 means internal server error.

Maybe you are looking for

  • Obiee 11g blocking.js script

    Hi , I am trying to implement blocking.js script for my analysis. and below is the code for claimsblocking.js script. I have placed the script in ..OracleBIPresentationServicesComponent\coreapplication_obips1\analyticsRes folder function validateAnal

  • Problem in accessing two different InitialContexts simultaneously

    Hi All I have a strange problem the scenario is as below I have two different web logic servers as server1 and server2 The Realm on server1 is user1 and password is pwd1 The Realm on server1 is user2 and password is pwd2 In my application on server1

  • Not able to add Search Item in Advanced Search Mappings of a Seeded Page.

    Hi, For one of the seeded pages (Manager Self Service -> Termination) the Search Item drop down in the Personalization of the Advanced Search Mappings does not show any value. My requirement is too add a new criteria to the Advanced Search and i crea

  • Background colour change for WebDynpro Application has to changed

    Hi All, One of my custom built web dynpro application background color has to be changed, is it possible to do that? Satish

  • Premiere Pro CC crashing on export

    Using a new iMac with 3.5 GHz Intel Core i7, 32 GB ram, and a NVIDIA GeForce GTX 780M 4096 MB. I have read a lot of the forums but nothing has worked for me. Every time I try to export the video I am editing it crashes. However, when I transfer the f