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]

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.

  • Set TimeOut for SwingWorker

    nice day,
    1/ how can I get real Html size in kB with intention to set as maxValue to ProgressMonitor
    2/ how can I set/synchronize current valueOfDownLoadedHtml in kB to ProgressMonitor throught downloading Html content
    3/ how can I set TimeOut for this Tast, (maybe ... could I use Timer)
    import java.awt.BorderLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.charset.Charset;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ProgressMonitor;
    import javax.swing.SwingWorker;
    public class ProgressMonitorDemo extends JPanel implements ActionListener, PropertyChangeListener {
        private static final long serialVersionUID = 1L;
        private ProgressMonitor progressMonitor;
        private JButton startButton;
        private JTextArea taskOutput;
        private Task task;
        private int sizeIn_kB = 0;
        class Task extends SwingWorker<Void, Void> {
            private String str;
            int progress = 0;
            public Task(String str) {
                this.str = str;
            @Override
            public Void doInBackground() {
                if (str.equals("Loads")) {
                    addBackgroundLoadsData();
                    setProgress(0);
                    while (progress < sizeIn_kB && !isCancelled()) {
                        progress += sizeIn_kB;
                        setProgress(Math.min(progress, sizeIn_kB));
                return null;
            @Override
            public void done() {
                if (str.equals("Loads")) {
                    Toolkit.getDefaultToolkit().beep();
                    startButton.setEnabled(true);
                    progressMonitor.setProgress(0);
        public void addBackgroundLoadsData() {
            InputStream in = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String charset ="";
            try {
                String UrlString = "http://java.sun.com/";
                URL url = new URL(UrlString);
                URLConnection conn = url.openConnection();
                sizeIn_kB = conn.getContentLength();
                charset = conn.getContentEncoding();
                conn.setRequestProperty("Accept-Charset", charset);
                in = conn.getInputStream();
                int len;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                in.close();
                String charEncoding = Charset.defaultCharset().name();
                //String fileEncoding = System.getProperty("file.encoding");
                //System.out.println("File Encoding: " + fileEncoding);
                //System.out.println("Char Encoding: " + charEncoding);
                //System.out.println("Char Encoding: " + Charset.availableCharsets());
                charEncoding = "cp1250";
                String groupImport = new String(bos.toByteArray(), charEncoding);
                conn = null;
            } catch (IOException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "Htlm error", JOptionPane.ERROR_MESSAGE);
            } catch (StringIndexOutOfBoundsException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "InputStream error", JOptionPane.ERROR_MESSAGE);
        public ProgressMonitorDemo() {
            super(new BorderLayout());
            startButton = new JButton("Start");
            startButton.setActionCommand("start");
            startButton.addActionListener(this);
            taskOutput = new JTextArea(5, 20);
            taskOutput.setMargin(new Insets(5, 5, 5, 5));
            taskOutput.setEditable(false);
            add(startButton, BorderLayout.PAGE_START);
            add(new JScrollPane(taskOutput), BorderLayout.CENTER);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        @Override
        public void actionPerformed(ActionEvent evt) {
            progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, 100);
            progressMonitor.setProgress(0);
            task = new Task("Loads");
            task.addPropertyChangeListener(this);
            task.execute();
            startButton.setEnabled(false);
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == null ? evt.getPropertyName() == null : "progress".equals(evt.getPropertyName())) {
                int progress = (Integer) evt.getNewValue();
                progressMonitor.setProgress(progress);
                String message = String.format("Completed %d%%.\n", progress);
                progressMonitor.setNote(message);
                taskOutput.append(message);
                if (progressMonitor.isCanceled() || task.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    if (progressMonitor.isCanceled()) {
                        task.cancel(true);
                        taskOutput.append("Task canceled.\n");
                    } else {
                        taskOutput.append("Task completed.\n");
                    startButton.setEnabled(true);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("ProgressMonitorDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new ProgressMonitorDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    See the session-descriptor element of weblogic.xml deployment descriptor:
    http://download.oracle.com/docs/cd/E21764_01/web.1111/e13712/weblogic_xml.htm#i1071981

  • Properly timeout a urlconnection?

    Hi,
    I have been struggling to find a way to timeout a UrlConnection when it hangs on trying to connect to a site . My application has around 10 threads with each thread creating a urlconnection object and getting the inputstream. My urlconnection hangs on occasion when trying to connect to certain sites.
    1. I'ved tried to create separate timer threads to launch the threads that actually make the connection. The timer threads would do a Thread.join() to the threads with the URLconnection object and do a Thread.interrupt() when it exceeds the join time limit.
    This approach does not actually kill the URL connection .
    And so I am left with a hanging URL connection.
    2. I've also tried using Socket to connect but the timeout is only for timing out when no activity is occurring. it doesn't timeout when it hangs on trying to connect. I don't know of any way to set the timeout before the connecting action occurs.
    3. I've thought about using Thread.stop() but according to the javadocs, it says this method is unsafe because it removes all the monitors.
    I s there a safe way to destroy a URLconnection after a certain amount of time?
    -Will

    My solution was your solution 1) with the additional wrinkle that I make sure that the threads that I am going to let run away are daemon threads (xx.setDaemon(true); --> before xx.start();).
    My experience is that they will eventually timeout by themselves (around 5 minutes or so; I did see a reference to 420 seconds at some point in my reading), but I am not willing to wait that long.
    So I just ignore them after my Thread.join(myTimeout) period, and let the GC handle them. Seems to work ...

  • URL,URLConnection,HttpURLConnection &&Session

    Hi,all
    I want to access a web page by URL/URLConnection/HttpURLConnection
    the page need a login user,it check the Session,if the session is null,then it redirect to the login page
    Now I have the user ID and Password ,and I can complete my login by URL Class
    but when I access the wanted page after I login,it's still return that the session is not set.
    below is the Code Segment,thanx in advance
    String urlStr = "http://buyc:8080/ecommerce/oa/login.jsp?txtUsername=sh001&txtPwd=111111&role=storeman";
    URL url = new URL(urlStr);
    HttpURLConnection hurlc =(HttpURLConnection) url.openConnection();
    hurlc.setFollowRedirects(true);
    hurlc.setInstanceFollowRedirects(true);
    hurlc.setUseCaches(true);
    hurlc.connect();//if check login successfully in login.jsp,it will redirect to a check page.
    InputStream is=hurlc.getInputStream();//
    byte tmpbyte[]=new byte[is.available()];
    int num=is.read(tmpbyte);
    String result=new String(tmpbyte);
    System.out.println("the " + num + ":" + result);

    IIRC, you use the UrlConnection's methods getHeaderField and getHeaderFields to get the cookies, and then setRequestProperty to set the cookies on subsequent connections. These methods are inherited by HttpUrlConnection.
    There may be a library out there to make this stuff easier, but I don't think it's in the standard libraries.

  • Setting timeout for all the web test scripts in the solution

    Hello,
    I have around 16 web test scripts (using VSTS 2010 ultimate version) in my project (in a solution). By default the timeout set for each request is 60 sec. I need to increase the timeout to 180 sec. Currently, I am clicking on each request and modifying
    the timeout parameter from the Properties window.
    Is there any common setting for timeout available which would be acting across all the scripts?
    Thanks.

    Hello,
    We only can set Timeouts for a separate request in Visual Studio Web Test. There is no way to set Timeout for all requests in VS IDE. But you can write you own logic code using
    Timeout Property in a web test plugin to set Timeout for all requests in a web test.
    About how to write a web test plugin, please see:
    How to: Create a Web Performance Test Plug-In
    Best regards,
    Amanda Zhu <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support
    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

  • Setting timeout for webservice

    hello all,
    I have made client program to connect to a webservice using dynamic url, my problem is i am unable to set the timeout of the webservice if anybody knows please let me know. my code is as follows.
    WebServiceClient ann = testpackage.TestClassService.class.getAnnotation(WebServiceClient.class);
    try {
    testpackage.TestClassService service = new testpackage.TestClassService(new URL("MY URL"), new QName(ann.targetNamespace(), ann.name()));
    testpackage.TestClass port = service.getTestClassPort();
    String result = port.getUserTask("HELLO");
    System.out.println(result);
    } catch (MalformedURLException ex) {
    using this code how can i set timeout at client side
    thanks in advance

    hi there thanks for your reply but your solution didn't worked for me. may be because of mistake in my question explanation i will explain it again
    WebServiceClient ann = testpackage.TestClassService.class.getAnnotation(WebServiceClient.class);
    try {
    testpackage.TestClassService service = new testpackage.TestClassService(new URL("MY URL"), new QName(ann.targetNamespace(), ann.name()));
    testpackage.TestClass port = service.getTestClassPort();
    String result = port.getUserTask("HELLO");
    System.out.println(result);
    } catch (MalformedURLException ex) {
    using this code i am calling my webservice and the function "getUserTask" which give me some output in return.
    now, what situation i am facing is whenever i make a call to the above function and if RTO occurs after the call of the function then my application comes in to a hang mode situation. and i am unable to do anything untill the reconnection of the network occurs.Either i have to wait for the reconnection or i have to terminate my applicartion.
    My desire is, i should be able to set my timeout period of a web service request. if no reply comes in the given time period then i should be able to raise any message to the user.
    I think ihave made myself a bit more clear.
    thanks for your reply once again.

  • Setting timeout for SOAP requests in a webservice client

    I am trying to set the timeout for a synchronous SOAP request sent to a Web Service deployed on weblogic 8.1 SP2. I tried setting timeout thru bindinginfo setTimeout() and also javax.xml.rpc.Stub _setProperty(). Both of them seem to be not working. I set the value to as low as 1 sec but i still donot get a timeout. Other properties/method from these two classes work fine though (like endpointaddress property in javax.xml.rpc.Stub and setVerbose flag to true in BindingInfo).
    Can someone please help.
    Thanks in Advance
    srini

    Our application calls the webservice provided by another company over the internet using the ssl. We use the wsdl url of the webservice on the destination while creating the port. If the destination is not available statement which creates the port blocks for around 4 minutes.
    I think the first network call gets the wsdl from the remote server. Thus we encounter delays before getting the stub created. How can I timeout such a calls.
    try {
    port = (new ServiceName_Impl(remoteWsdlURL)).getServiceNameSoap();
    } catch (IOException e) {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to get remaining time for baton after setting timeOut property

    Hello,
    Is it possible to get the remaining time for baton after setting timeOut, or do I have to maintain a separate Timer for that?
    Been following this excellent tutorial here http://tv.adobe.com/watch/adc-presents/create-shared-forms-in-livecycle-collaboration-serv ice/

    Thanks Nigel, before reading your reply, I came up with something like this, but it seems extending the Baton class is not enough, as I would need my own BatonProperty as well that uses this extended Baton class...
    Also attempted to get some help here http://stackoverflow.com/questions/7116814/actionscript3-lccs-how-to-access-property-paren t-class-protected-var/7116882#7116882
    Could this be made into a feature request for Baton and BatonProperty, se we could easily get the remaining time please?   I guess I can wait for a future release.
    /custom as file /
    package com.mysite.BatonExtender
         import com.adobe.rtc.sharedModel.Baton;
         import flash.events.TimerEvent;
         public class BatonExtender extends Baton
              public function BatonExtender()
              super();
              _autoPutDownTimer.addEventListener(TimerEvent.TIMER,countDown);    
              trace("CURRENT TIMER:"+_autoPutDownTimer.currentCount);
              trace("BATONEXTENDER added");
              public function countDown(p_evt:TimerEvent):void {
                   trace("TRACING START countDown....");
                   if (_autoPutDownTimer.running) {
                        trace(_autoPutDownTimer.currentCount);
                        //sharedTimer.value = String(90 - _autoPutDownTimer.currentCount);
                   trace("TRACING END....");

  • Set timeout in JSP?

    Hi, is possible to set timeout in a JSP?? For instance, when the user clicks on the a hyperlink it will open a page and after a time interval, the page will auto close and call the same JSP function to open the same page but with different values in it...

    Hmm.. do u think it will work whereby the user will just need to click on a hyperlink once, then it will pass different value to a Javascript function each time. Coz the hyperlink that the user clicks will get the values from a text file (all the values retrieved are stored in a Vector.) which is passed to the Javascript function for loading an applet. As the applet will load some data out, hence, i need to wait till the applet finish loading, then i can call the same Javascript function again, but a different value...

  • Set timeout for completion of each thread

    i have a requirement where i need to start n threads and set timeout for completion of each thread.
    if the thread is not executed successfully(because of timeout ) i have to enter in audit table that it failed because of timeout
    if executed successfully update audit table with success.
    can some one give me solution for this using ThreadPoolExecutor available jdk1.5

    Add a scheduled task to time out the task (when it would time out). Keep the Future and cancel it if the task completes successfully.
    final Future future = executor.schedule(new TimeoutTask(), timeoutMS, TimeUnit.MILLI_SECONDS);
    executor.execute(new Runnable() {
      public void run() {
          try {
             task.run();
          } finally {
             future.cancel(true);
    });

  • Set timeout for URL connection in java1.4

    hi
    I want to set timeout for URL connection in java 1.4..
    java 5.0 provides with a setTimeout(int ) method but how should it be done in 1.4 environment
    Thanks in advance
    sneha

    sun.net.client.defaultConnectTimeout (default: -1)
    sun.net.client.defaultReadTimeout (default: -1)
    See the [Networking Properties|http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html].

  • Need help about setting timeout webservice client.

    Hi,
    I trying to set timeout before make call to the webservices, my target webservice is deployed on WebLgic server 8.14 (service pack 4). Nothing just Thread.sleep for 1 min. then return some string. Here is my client code. I use the proxy generated by the workshop testing browser, "Java proxy" button.
    public static void main(String a[]) {
    try {
    EjbTimeout_Impl proxy = new EjbTimeout_Impl();
    EjbTimeoutSoap_Stub myStub = (EjbTimeoutSoap_Stub)proxy.getEjbTimeoutSoap();
    BindingInfo bInfo = (BindingInfo)myStub._getProperty("weblogic.webservice.bindinginfo");
    System.out.println(bInfo.getTimeout()); // print out '-1' no timeout I guess
    bInfo.setTimeout(5); //secs
    System.out.println(bInfo.getTimeout()); // print out '5', value change accepted
    myStub._setProperty("weblogic.webservice.rpc.timeoutsecs", "5");
    System.out.println(myStub._getProperty
    ("weblogic.webservice.rpc.timeoutsecs")); // also print '5'
    String ss = myStub.sayHello("WEBLOGIC");
    System.out.println(ss);
    } catch (Exception e) {
    System.out.println(e.toString());
    As you see the timeout value is changed but when I call webservice from this client everything is fine. The output string ruturn from webservice is printed out after Thread.sleep(60000).
    Are there any missing things about this client code, my webservice code is quite simple, or if there is some way else to achieve this ???
    Many thanks.

    Before you use the JMS, you need to deploy some drivers related to specific MQseries, Kindly ensure that proper driver are deployed....
    If you use MQSeries 53x.xxx, you must enter the following JAR files in aii_af_jmsproviderlib.sda.
    com.ibm.mq.jar, com.ibm.mqbind.jar, com.ibm.mqjms.jar, connector.jar (use the JAR file from the J2EE client directory)
    check this link it will give you more inofmration
    http://help.sap.com/saphelp_nw04/helpdata/en/cd/d85a9d6fab7d4dbb7ae421f710626c/content.htm
    check this to get the condifuration the JMS
    How to use conversion modules in JMS - https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/f02d12a7-0201-0010-5780-8bfc7d12f891
    Ref How To Use the Content Conversion Module in JMS Adapter - https://websmp106.sap-ag.de/~form/sapnet?_SHORTKEY=01100035870000582377&

  • Set TIMEOUT on OCCI sql query using ?

    Is there a way to set a timeout on a sql query using OCCI ?

    OCCI does not provide an API to set timeouts on SQL Queries.
    You can use the CREATE PROFILE command and assign resources at
    a user level. The restrictions may be applied to memory/resources which
    in turn would control the SQL execution time. Please check the
    CREATE PROFILE command.
    Rgds
    Amogh

  • Set timeout on socket?

    If i want to set timeout on a clientsocket how do i do?
    I know you use setsotimeout, but i don't know how
    Can someone post a short samplecode?
    Thanks!
    (something like this but with timeout)
    Socket MyClient;
    try {
    MyClient = new Socket("Machine name", PortNumber);
    catch (IOException e) {
    System.out.println(e);
    }

    Can you stop saying TRIPPLE POSTING BLA BLA BLA and
    help me instead?
    Stop multiposting and cross posting you fool.
    I have said like 100 times i DON'T get it, it would
    be nice if you posted some sample code so i can see
    what i have been doing wrong.
    Post your code and we can see where you have gone wrong. Please use your original thread for this.

Maybe you are looking for

  • Help building image swap in flash cs4?

    Hello all, I've been trying to research 'flash cs4 image swap' but most everything I find is related to dreamweaver, so I appreciate anyone's help to point me in the right direction. I have a project in which I have an opening scene of a main image a

  • Can I keep the power cord plugged in when battery reaches 100%l?

    Hello, I'm assuming the battery stops recharging when it reaches 100%, right? In other words I can keep the power chord plugged in without any risk of "overcharging". Correct? Thanks.

  • Write/read file in OOP

    Hello, I have to make class that reads/creates tdms file I know OOP concepts from C++ and I ve seen write and safe class to file example  in labview but I have no idea haw to make it and what are benefits of using OOP in this case.. I thought about c

  • Designing an Airport Network

    Question 1. I have the document: "Designing Airport Networks Using Airport Utility" The cover says "Mac OSX V 10.5" I am running 10.4.11. Can I use that document? Is there another for 10.4.11? Question 2. The directions that come with the Airport Ext

  • Messages in Headstart

    Hi, Currently I have a post-insert trigger that does some inserting to the database. Before every transaction there is a message that tells that users the percentage complete ie. message('Processing...30%');SYNCHRONIZE; However this doesn't appear on