URLConnection

I have a thread that connects to a number of web-pages, downloads them, parses and after that some additional actions. The problem is that I can�t control any grapical components while the thread is executing, even if I set it to lowest possible priority. I want to update a simple JLabel with text showing me what the thread is currentry doing. Calling label.repaint() is not helping. I am calling label.setText from thread.run().
Regards
SlackerJr

It worked by calling paintImmidiatly, like this:
private void updateLabel(){
Dimension dim = statusLabel.getSize();
statusLabel.paintImmediately(0, 0, dim.width, dim.height);
/slackerJr

Similar Messages

  • Can some one give me clear answer how to set timeouts on URLConnection ?

    I am amazed why Sun did not specify a simple method like setReadTimeout
    on URLConnection or provide a way to get refernce to the underlying socket objet. By default the timeout is infinite!
    I am using JDK 1.4 and these appraoches:
    -Dsun.net.client.defaultConnectTimeout=<value in milliseconds>
    -Dsun.net.client.defaultReadTimeout=<value in milliseconds>
    also don't work.
    I do not have access to Socket object. Please help.
    I am using URLConnection in my client application on HTTPS and doing heavy load form POST processing. I tried
    Sockets as well but they don't work. URLConnection works perfectly fine except for the timeouts nightmare.

    OK this might sound crazy but you may have been onto it right from the start. I was having the exact same (frustrating) problem with the URLConnection waiting forever on a dead server and no way to terminate it. I tried something like what you said in your first post:
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    and it worked. I played around with the number and it it was apparent to the naked eye that it was working (if you can believe that...).
    Of course, I'm using JDK 1.4.1_01 by now, so this might be different now.
    ttfn.

  • Sending email using URL and URLConnection

    I have been having trouble trying to send an email using URL.
    I have specified the mail host using: mailHost = Options.getProperty("mailHost", "mail.myisp.com");
    and tried to send the email using this:
    try
    try
    URL u = new URL("mailto:"+recipient);
    URLConnection c = u.openConnection();
    c.setDoInput(true);
    c.setDoOutput(true);
    c.connect();
    PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
    out.print("From:\"ME\" \n");
    out.print("Subject: Stuff \n");
    out.print("blah blah blah");
    out.close();
    catch etc. . .
    I recieve the email with the subject line there, but the actual body of the email is empty. Anyone know what I have done wrong? This is part of a standalone application that was turned into an .exe with jbuilder9.

    That worked, thanks!
    Out of curious, why the surprise that it worked?
    Its not that bad is it?Yeah, I didn't know that mailto: support was there either, is all. The blank line thing is just common in HTTP and sendmail so, I figured that would be the solution.
    I don't know that it's bad... if it works. Generally, the JavaMail APIs are a more robust way of sending mail, but if mailto: URLs work, and it's simple mail, then I see no reason not to use it.

  • Copy a file from server to the client - URLConnection to a Portal page

    Hello:
    I have an application running on the client side. When the app startup it must open a file which is at the server side, to be more specific, the file is at KM content of the portal.
    I try to read it with URLConnection to copy the file from the server to the client, the app will do it, but "Server returned HTTP response code: 401 for URL:"
    If you copy&paste the url's file directly on the browser (http://host:port/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/ImagenesIM/file.txt) a login popup (look and feel windows) is display. After entering the user and psw the file is open without problem.
    Any idea what can I use or how do it ?.
    I think that probably I have to move the app to a was directory instead of portal directory.
    The app is execute via *.jnlp with a link at a portal page.
    Thanks a lot for your time.

    Javier,
    401 means authentication error, i.e. your application is not authenticated to KM.
    What you can do? Actually, it depends. Check current cookies in your application, probably there are SSO coockie or J2EE authentication cookie. You may try to set this cookies in URLConnection (via addHeader). Otherwise you have to supply authentication creadentials to URLConnection (also via addHeader, most probably, via Basic HTTP authentication scheme).
    Valery Silaev
    EPAM Systems
    http://www.NetWeaverTeam.com

  • When using URLConnection read input stream error

    hi,
    In my applet I build a URLConnection, it connect a jsp file. In my jsp file I refer to a javaBean. I send two objects of request and response in jsp to javaBean. In javabean return output stream to URLConnect. At that time a error happened.WHY???(Applet-JSP-JAVABean)
    Thanks.
    My main code:
    APPLET:(TestApplet)
    URL url = new URL("http://210.0.8.120/jsp/test.jsp";
    URLConnection con;
    con = url .openConnection();
    con = servlet.openConnection();
    con.setDoInput( true );
    con.setDoOutput( true );
    con.setUseCaches( false );
    con.setRequestProperty( "Content-Type","text/plain" );
    con.setAllowUserInteraction(false);
    ObjectOutputStream out;
    out = new ObjectOutputStream(con.getOutputStream());
    Serializable[] data ={"test"};
    out.writeObject( data );
    out.flush();
    out.close();
    //until here are all rigth
    ObjectInputStream in = new ObjectInputStream( con.getInputStream() );//happened error
    JSP:
    TestBean testBean = new TestBean ();
    testBean .execute(request, response);
    JAVABEAN:
    public void execute( HttpServletRequest request,
    HttpServletResponse response )
    ObjectInputStream in = new ObjectInputStream( request.getInputStream() );
    String direct = (String) in.readObject();
    System.out.prinltn("direct");
    ObjectOutputStream out = new ObjectOutputStream( response.getOutputStream() );
    SerializableSerializable[] data ={"answer"};
    out.writeObject( data );
    out.flush();
    out.close();
    Error detail:
    java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:729)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:251)
         at TestApplet.postObjects(TestApplet.java:172)

    you have to pay attention to the sequence of opening the streams.
    The following example is: client sends a string to server, and servlet sends a response string back.
    client side:
             URL url = new URL( "http://152.8.113.149:8080/conn/servlet/test" );
             URLConnection conn = url.openConnection();   
             System.out.println( "conn: " + conn );
             conn.setDoOutput( true );
             conn.setDoInput( true );
             conn.setUseCaches( false );
             conn.setDefaultUseCaches (false);
             // send out a string
             OutputStream out = conn.getOutputStream();
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             oOut.writeObject( strSrc ); 
             // receive a string
             InputStream in = conn.getInputStream();     
             ObjectInputStream oIn = new ObjectInputStream( in );
             String strDes = (String)oIn.readObject();server side
             // open output stream
             OutputStream out = res.getOutputStream();  
             ObjectOutputStream oOut = new ObjectOutputStream( out );
             // open input stream and read from client
             InputStream in  = req.getInputStream();
             ObjectInputStream oIn = new ObjectInputStream( in );
             String s = (String)oIn.readObject();
             System.out.println( s );
             // write to client
             oOut.writeObject( s + " back" ); I have the complete example at http://152.8.113.149/samples/app_servlet.html
    don't forget to give me the duke dollars.

  • 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

  • Setting Timeout  in URLConnection/HttpURLConnection

    Hi all,
    I am trying to open a connection a website using the java.net.HttpURLConnection.
    Please tell me what is the default timeout (how much time it will wait for getting reply ) and how we can change the
    default value. Please help me.
    Thanks in advance.

    This seems to be what you are looking for.
    [http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29|http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29]

  • Need Help in reading data from URLConnection in servlets

    hi i created GUI which sends d username n password to the servlets via URLConnection.n am sending the same to Server program via sockets.but when i read d data in the servlet am getting only null value...need help here....
    This is my button's ActionPerformed code
    private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
    String uname = UserName.getText();
    char [] pwd = PassWord.getPassword();
    String pword = new String(pwd);
    try
    String url = "http://localhost:8080/MIMServlets/hit";
    URL ucon = new URL(url);
    URLConnection conn = ucon.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
              conn.setUseCaches (false);
    conn.setDefaultUseCaches (false);
    conn.setRequestProperty("Content-Type", "text/plain");
    System.out.println(uname);
         System.out.println(pword);
         PrintWriter out = new PrintWriter( conn.getOutputStream() );
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    conn.getInputStream()));
         out.print(uname);
    out.print(pword);
         out.close();
    String inputLine = in.readLine();
    Status.setText(inputLine);// TODO add your handling code here:
    }catch(MalformedURLException e)
    System.out.println("Exception"+e);
    catch(IOException e1)
    System.out.println("Exception"+e1);
    This is my Servlet code........
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class MIMServlets extends HttpServlet
    PrintWriter out,out1;
         BufferedReader in,in1;
         String host = "localhost";
         String fromServer = "";
         String username,password;
         int a;
         public void init()
    out=null;
    out1=null;
    public void doPost(HttpServletRequest request,HttpServletResponse
                   response)throws ServletException,IOException
              response.setContentType("text/html");
              out=response.getWriter();
              try{
              InetAddress address = InetAddress.getByName(host);
    Socket theSocket = new Socket(address, 4444);
    out1 = new PrintWriter(theSocket.getOutputStream(),true);
    in = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
    in1 = new BufferedReader(new InputStreamReader(request.getInputStream()));
              String username = in1.readLine();
              String password = in1.readLine();
    System.out.println(username);
              System.out.println(password);
    out1.println(username);
              out1.println(password);
              out1.println("Yahoo");
              out1.flush();
    while ((fromServer = in.readLine()) != null)
    out.println("From Server: " + fromServer);
              break;
         out1.close();
    in.close();
    theSocket.close();
         }catch(IOException e)
    System.out.println("Exception");
    System.exit(-1);
              public void destroy()
         out.close();
    thanks in advance.......

    Follow below example to using FM 'READ_TEXT'
    DATA  BEGIN OF i_tlines OCCURS 0.
            INCLUDE STRUCTURE tline.
    DATA  END   OF i_tlines.
    DATA: w_textname(70) TYPE c.
      w_textname = vbdkr-vbeln.
      CALL FUNCTION 'READ_TEXT'
        EXPORTING
          client                        = sy-mandt
          id                            = 'Z006'
          language                      = 'E'
          name                          = w_textname
          object                        = 'VBBK'
        TABLES
          lines                         = i_tlines.
      IF sy-subrc = 0.
        READ TABLE i_tlines INDEX 1.
        t_in-m1 = i_tlines-tdline.   "Now t_in_m1 will have the value
      ENDIF.
    Regards,
    SaiRam

  • URLConnection setRequestProperty doesn't seem to work

    G'day, I am trying to set a URLConnection property for proxy authentication. Here's a simple test I've created:
    import java.net.*;
    public class ProxyTest {
        public static void main(String[] args) {
            try {
                System.setProperty("http.proxyHost", "192.168.107.24");
                System.setProperty("http.proxyPort", "3128");
                URL url=new URL("http://google.com");
                URLConnection uc = url.openConnection ();
                uc.setRequestProperty( "Proxy-Authorization", "foobar");
                System.out.println("Proxy-Authorization is: " + uc.getRequestProperty("Proxy-Authorization"));
                uc.connect();
            } catch (Exception e) {
                e.printStackTrace();
    }This always gives my "Proxy-Authorization is null". I have tested this on java 1.6 and 1.5, on a linux system and a windows xp system. In my real app the url connection always gives me 407 unauthorized, I have used tcpdump to check just in case the Proxy-Authorization is being sent, but it isn't.
    I am probably missing something simple - can anyone see what it might be? Cheers.

    Try the below.
    package test;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    * @author asiri_godage
    public class Main {
    public static void main(String[] args) {
    System.out.println("HHHHH");
    String message;
    System.out.println(System.getProperty("proxySet"));
    System.getProperties().put( "proxySet", "true" );
    System.getProperties().put( "proxyHost", "proxy.server.com" );
    System.getProperties().put( "proxyPort", "8080" );
    String password = "UserName:LoginPassword";
    String encodedPassword = base64Encode( password );
    try{
    URL u = new URL("[http://www.rarlab.com/rar/wrar390.exe]");
    URLConnection uc = u.openConnection();
    {color:#000000}uc.setRequestProperty( "Proxy-Authorization", " Basic " + encodedPassword );{color}
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
    throw new IOException("This is not a binary file.");
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
    bytesRead = in.read(data, offset, data.length - offset);
    if (bytesRead == -1) {
    break;
    offset += bytesRead;
    in.close();
    if (offset != contentLength) {
    throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    String filename = "";
    filename = "C:" + u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
    }catch(Exception e){
    e.printStackTrace();
    private static String base64Encode(String password) {
    char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
    char [] data= password.toCharArray();
    char[] out = new char[((data.length + 2) / 3) * 4];
    // 3 bytes encode to 4 chars. Output is always an even
    // multiple of 4 characters.
    for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
    boolean quad = false;
    boolean triple = false;
    //convert to unsigned byte
    int val = (0xFF & (int) data);
    val <<= 8;
    if ((i + 1) < data.length) {
    val |= (0xFF & (int) data[i + 1]);
    triple = true;
    val <<= 8;
    if ((i + 2) < data.length) {
    val |= (0xFF & (int) data[i + 2]);
    quad = true;
    out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
    val >>= 6;
    out[index + 2] = alphabet[(triple ? (val & 0x3F) : 64)];
    val >>= 6;
    out[index + 1] = alphabet[val & 0x3F];
    val >>= 6;
    out[index + 0] = alphabet[val & 0x3F];
    String sout=new String(out);
    return sout;

  • URLConnection does not create file

    Hello,
    I have a server and I'm using URLConnection to create a file on the server and write some text into it. However, after I run my program, no exception is thrown, but also no file is created on the server!!!
    Here is the source code:
    URLConnection destinationConnection=destinationURL.openConnection();
    destinationConnection.setDoOutput(true);
    destinationConnection.connect();
    destinationWriter=new OutputStreamWriter(destinationConnection.getOutputStream());
    destinationWriter.write(URLEncoder.encode(actions[counter].toString(),"UTF-8"));
    destinationWriter.close();Thank you very much for your help!

    You can only create a file if the server lets you. What's on the other side of that URL? Is it a servlet (or other server-side code) that receives content and writes it to a file? Are you sure it's working?
    If the URL is to a plain file...you can do that, but you'd have to set the HTTP method to PUT, and most servers don't support that anyway.
    I don't think that an exception would necessarily be thrown if you can't write to a file. Maybe it would just return standard HTTP response code indicating that file writing isn't allowed. Or maybe if the server side functionality is broken, it would just report that everything is OK even when it isn't.
    This isn't somethign you can debug purely on the client side.

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

  • Help with Java Memory Leak in URLConnection

    Hi everyone,
    I can't seem to find the memory leak in the below code, if anyone could help, i would greatly appreciate it. The jist of the code is: I open up a URLConnection to update a ColdFusion page that takes in URL parameters passed in my URL. Then, I get the response. I also check for proxy usage and take that into consideration when making the connection.
    I have one class to handle the Connections, Connect.java:
         * Connection using Username and Password, as well as boolean option to use Basic Proxy Authentication
         public Connect(String pHost, String pPort, String urlString,
                             String pUsername, String pPassword, boolean useProxy) {
              this.pHost = pHost;
              this.pPort = pPort;
              this.urlString = urlString;
              this.pUsername = pUsername;
              this.pPassword = pPassword;
              this.useProxy = useProxy;
         * Get the Input Stream from the Connection given a specific URL
         public java.io.InputStream getInputStream(String urlString) {
              if (urlString == null) urlString = this.urlString;
                 exDialog = new ExceptionDialog(new javax.swing.JFrame());
              try {
                   String auth = "";
                   if (useProxy) {
                        System.getProperties().put("proxySet", "true");
                        System.getProperties().put("proxyHost", pHost);
                        System.getProperties().put("proxyPort", pPort);
                        String authString = "";
                        if (pUsername != null && pUsername != "") authString = pUsername + ":";
                        else authString = "username:";
                        if (pPassword != null && pPassword != "") authString = authString + pPassword;
                        else authString = authString + "password";
                        auth = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes());
                   java.net.URL url = new java.net.URL(urlString);
                   java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
                   if (useProxy) conn.setRequestProperty("Proxy-Authorization", auth);
                   conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");
                   conn.setDoInput( true );
                   conn.setDoOutput( true );
                   conn.connect();
                   return conn.getInputStream();
              } catch (java.io.IOException ioe) {
                   exDialog.showForThrowable(ioe.toString(),ioe);
                   return null;
         }I call the code in Download.java:
    Connect conn = new Connect(sm.pHost, sm.pPort, null, sm.pUser, sm.pPass, sm.useProxy);
    new BufferedReader(new InputStreamReader(conn.getInputStream(sUpdateURL)));
    in.close();For some reason, as I loop through this call, the memory footprint of my program grows through every iteration, eventually resulting in a Java Out of Memory error. I can't track the leak down and it's fairly frustrating. If anyone can help, that would be greatly appreciated. Thanks!

    One place there might be a memory leak is in the line
    exDialog = new ExceptionDialog(new javax.swing.JFrame());Even though the JFrame object goes out of scope when the ExceptionDialog method returns, JFrames stay around until they are closed, even though in this case it isn't even shown on the screen.

  • How to use HTTPS with JSSE URLConnection in servlet

    Hi, I have a servlet that calls another servlet using the URLConnection class. This seems to work very well if I am using http. However when trying to call it using https using JSSE I get the following error:
    "javax.net.ssl.SSLHandshakeException: untrusted server cert chain."
    The following is the code that I am using in the servlet:
              java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
              System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
              this.servlet = new URL(servletURL);
              URLConnection conServlet = servlet.openConnection();
    Both of these servlets are under IIS on my machine. I am able to execute each of the servlets from the browser using https directly. Does this sounds like an SSL certifcate problem or is that something in the Java code? Any ideas greatly appreciated.

    Hi,
    Perhaps you can create your own trust manager. I've found this example in another newsgroup: (please note that this example trusts everyone, but you can modify the trust manager as you wish)
    if (putUrl.startsWith("https"))
      //set up to handle SSL if necessary
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
      System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      //use our own trust manager so we can always trust
      //the URL entered in the configuration.
      X509TrustManager tm = new MyX509TrustManager();
      KeyManager []km = null;
      TrustManager []tma = {tm};
      SSLContext sc = SSLContext.getInstance("ssl");
      sc.init(km,tma,new java.security.SecureRandom());
      SSLSocketFactory sf1 = sc.getSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory (sf1);
    m_url = new URL (putUrl);
    class MyX509TrustManager implements X509TrustManager {
    public boolean isClientTrusted(X509Certificate[] chain) {
      return true;
    public boolean isServerTrusted(X509Certificate[] chain) {
      return true;
    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }Hope this helps,
    Kurt.

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

  • HttpURLConnection and URLConnection

    hi,
    what's the difference between HttpURLConnection and URLConnection ?
    When should I use the first and when the second one ?
    thanks

    The Javadoc shows the relationship. Cast a URLConnection to an HttpURLConnection when the URL protocol is HTTP.

  • Diffrence between socket connection and URLConnection

    hy friends,
    though, i know and often work on it but it might be more conceptual for me to know your perception.
    by the way, what are the main points which diffrentiate the connection between client and server using
    1) sokets which in tern using ClientSocket,ServerSocket... classes
    2) URL directly which in tern using HttpURLConnection,URLConnection...classes
    any help would greatly appreciated

    1) sokets which in tern using ClientSocket,ServerSocket... classesYou mean 'sockets', and 'Socket', not 'ClientSocket'. Sockets speak TCP.
    2) URL directly which in tern using HttpURLConnection,URLConnection...classesHttpURLConnection speaks HTTP which is an application protocol layered over TCP.

Maybe you are looking for