Http请求超时的一种处理方法[通俗易懂]

Http请求超时的一种处理方法[通俗易懂]URLConnection类常见的超时处理就是调用其setConnectTimeout和setReadTimeout方法:setConnectTimeout:设置连接主机超时(单位:毫秒)setRea

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

URLConnection类常见的超时处理就是调用其setConnectTimeout和setReadTimeout方法:

  1. setConnectTimeout:设置连接主机超时(单位:毫秒)  
  2. setReadTimeout:设置从主机读取数据超时(单位:毫秒)

还有一种比较另类的就是利用java Object对象的wait()和notify()、notifyAll()方法,利用线程的等待和通知机制处理urlConnection的超时,下面直接贴代码:

public class HttpConnProcessThread implements Runnable {

    public boolean isStop = false;

    public boolean readOK = false;

    private HttpURLConnection reqConnection = null;
    
    public Thread readingThread;

    private int readLen;

    private String msg = null;
        
    private String reqMethod;

    private byte[] data;
    
    /**
     * ReadThread constructor comment.
     */
    public HttpConnProcessThread(HttpURLConnection reqConnection, String msg, String reqMethod ) {
        super();
        this.reqConnection = reqConnection;
        this.msg = msg;
        this.reqMethod = reqMethod;
    }

    public void run() {

        InputStream input = null;
        OutputStream output = null;

        try{
            //reqConnection.connect();
            output = reqConnection.getOutputStream();
            if ("post".equalsIgnoreCase(reqMethod) && msg != null && msg.length() >0) 
            {
                output.write(msg.getBytes());
                output.close();
                output = null;
            }

            // 处理HTTP响应的返回状态信息
            int responseCode = reqConnection.getResponseCode();// 响应的代码if( responseCode != 200 )
                System.out.println("connect failed! responseCode = " + responseCode + " msg=" + reqConnection.getResponseMessage());
            
            input = reqConnection.getInputStream();

            int len;
            byte[] buf = new byte[2048];
            readLen = 0;
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
       // 读取inputStream
            while (!isStop) 
            {
                len = input.read(buf);
                if (len <= 0) 
                {
                    this.readOK = true;
                    input.close();
                    data=outStream.toByteArray();
                    break;
                }
                outStream.write(buf, 0, len);  
                readLen += len;
            }
        }
        catch( IOException ie)
        {}
        catch(Exception e)
        {}
        finally
        {
            try{
                reqConnection.disconnect();
                if( input != null )
                    input.close();
                if( output != null )
                    output.close();
                
                //唤醒线程,跳出等待
                wakeUp();
            }catch(Exception e)
            {
                
            }
        }
    }

    public String getMessage(){
        if (!readOK) //超时
        {
            return "";
        }
        
        if (readLen <= 0) {
            return "";
        }
        return new String(data, 0, readLen);
    }

    public void startUp() {
        this.readingThread = new Thread(this);
        readingThread.start();
    }


    //唤醒线程,不再等待
    private synchronized void wakeUp() {
        notifyAll();
    }

    public synchronized void waitForData(int timeout) 
    {
        try {
            //指定超时时间,等待connection响应
            wait(timeout);
        } 
        catch (Exception e) 
        {
        }
            
        if (!readOK)
        {
            isStop = true;
            try{
                //中断线程
                if( readingThread.isAlive() )
                    readingThread.interrupt();
            }catch(Exception e)
            {
                
            }
        }
    }

    public static main(String[] args){
        String msg="";
        URL reqUrl = new URL("http://127.0.0.1:8080/");

        // 建立URLConnection连接
        reqConnection = (HttpURLConnection) reqUrl.openConnection();
        HttpConnProcessThread rec = new HttpConnProcessThread(reqConnection, msg, "post" );
        rec.startUp();
   // 如果顺利连接到并读完数据,则跳出等待,否则等待超时 rec.waitForData(
2000); String retMessage = rec.getMessage(); } }

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/167426.html原文链接:https://javaforall.net

(0)
上一篇 2022年8月2日 下午4:46
下一篇 2022年8月2日 下午5:00


相关推荐

  • instant java,关于java:Format Instant to String

    instant java,关于java:Format Instant to String我正在尝试使用新的 java8time api 和模式将 Instant 格式化为 String Instantinsta Stringout DateTimeForm ofPattern yyyy MM ddHH mm ss format instant 使用上面的代码我得到一个异常 它抱怨一个不受支持的字段 java time temporal Unsup

    2025年7月6日
    8
  • 要想成功先脱去幼稚

    要想成功先脱去幼稚记者问:“人要活得明白通透需要时间吗?”郭德纲答:“不需要时间,需要经历。一个人六十了,从小没挨过打,没人说过什么难听话。走大街上,别人瞪了一眼,咔,死了;一个人从小每天挨十个嘴巴,天天挨骂,长大了铁罗汉,抗压能力高。”经历过大风大浪真的可以帮助我们变得成熟稳重,那么问题来了,我们每天经历不了那么多的风浪,怎么办?这个时候,我认为应该先提高自己的思想。人不成熟的五大特征:人不成熟的第一…

    2022年6月2日
    35
  • python 字符串转列表,列表转字符串

    python 字符串转列表,列表转字符串1.字符串转列表python的split()函数个人认为是个相当神奇的存在。比如你有一串字符串需要解析。就可以用split()想去掉字符串里面的回车键:str=a.split(‘\n’)想去掉前两个a字符str=a.split(‘a’,2)就是这么神奇。返回的str还是个列表。2.列表转字符串若想将python的列表转化为字符串,直接去掉‘[…

    2022年5月20日
    36
  • int类型的长度是多少_强制转换成int类型

    int类型的长度是多少_强制转换成int类型Int16意思是16位整数(16bitinteger),相当于short占2个字节-32768~32767Int32意思是32位整数(32bitinteger),相当于int占4个字节-2147483648~2147483647Int64意思是64位整数(64bitinterger),相当于longlong占8个字节…

    2026年2月4日
    3
  • 异步fifo与同步fifo_161是同步还是异步清零

    异步fifo与同步fifo_161是同步还是异步清零异步FIFO设计

    2022年8月13日
    6
  • 中断之NVIC

    中断之NVIC简单的介绍一下NVIC,有点枯燥乏味

    2022年5月8日
    60

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号