当前位置: 代码网 > it编程>编程语言>Java > java发送http请求时如何处理异步回调结果

java发送http请求时如何处理异步回调结果

2024年06月12日 Java 我要评论
java发送http请求时处理异步回调结果maven依赖<dependency><groupid>org.apache.httpcomponents</groupid&g

java发送http请求时处理异步回调结果

maven依赖

<dependency>
			<groupid>org.apache.httpcomponents</groupid>
			<artifactid>httpasyncclient</artifactid>
			<version>4.1.1</version>
		</dependency>

1.线程类 负责处理业务

package com.ruoyi.test;
 
import java.io.unsupportedencodingexception;
 
/**
 * created with idea
 * author:qinwei
 * date:2019/4/10
 * time:10:28
 */
public class business extends thread{
    // 回答1+1,很简单的问题不需要线程
    public int add(int num1, int num2) {
        return num1 + num2;
    }
 
    // 重写run方法
    @override
    public void run() {
        // 回答地球为什么是圆的
        askquestion();
        super.run();
    }
 
    // 回调接口的创建,里面要有一个回调方法
    //回调接口什么时候用呢?这个思路是最重要的
    //
 
    public static interface calls {
        public void call(string question);
    }
 
    // 回调接口的对象
    calls calls;
 
    // 回答地球为什么是圆的
    private void askquestion()  {
        system.err.println("开始查找资料!");
        try {
           // 业务请求处理
            string succes = test.main();
 
            // 把答案返回到回调接口的call方法里面
            if (calls!=null) {//提问者实例化callphone对象,相当于提问者已经告诉我,我到时用什么方式回复答案
                //这个接口的方法实现是在提问者的类里面
                calls.call(succes);
            }
        } catch (exception e) {
            e.printstacktrace();
        }
 
 
    }
}

2.请求接口类

package com.ruoyi.test;
 
import com.ruoyi.common.json.jsonobject;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.client.methods.httppost;
import org.apache.http.concurrent.futurecallback;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.nio.client.closeablehttpasyncclient;
import org.apache.http.impl.nio.client.httpasyncclients;
import org.apache.http.util.entityutils;
 
import java.io.ioexception;
import java.io.unsupportedencodingexception;
import java.util.concurrent.countdownlatch;
 
/**
 * created with idea
 * author:qinwei
 * date:2019/4/10
 * time:9:15
 */
public class test {
 
    public static string main() throws unsupportedencodingexception {
        final string[] resdata = new string[1];
        closeablehttpasyncclient client = httpasyncclients.createdefault();
        client.start();
        final countdownlatch latch = new countdownlatch(1);
        final httppost post = new httppost("http://127.0.0.1:8088/login");
        string param1="loginname=6210308024916652&password=123456&captcha=10";
        jsonobject param2= new jsonobject();
        param2.put("loginname", "6210308024916652");
        param2.put("password", "123456");
        param2.put("captcha", "4");
        //设置请求头    这里根据个人来定义
        post.addheader("content-type", "application/json; charset=utf-8");
        post.setheader("accept", "application/json");
        stringentity stringentity = new stringentity(param2.tostring());
        post.setentity(stringentity);
        //执行
        client.execute(post, new futurecallback<httpresponse>() {
            //执行异步操作  请求完成后
            @override
            public void completed(final httpresponse response) {
                latch.countdown();
                //响应内容
                int a = response.getstatusline().getstatuscode();
                system.out.println("状态码:"+a);
                if (a == 200) {
                    httpentity entity = response.getentity();
                    try {
                        resdata[0] = entityutils.tostring(entity);
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                    system.out.println("成功!");
                } else {
                    try {
                        //输出响内容
                        system.out.println(response.getstatusline().getstatuscode()
                                + "  " + entityutils.tostring(response.getentity(), "utf-8"));
                    } catch (ioexception e) {
                        e.printstacktrace();
                    }
                }
            }
 
            //请求失败处理
            @override
            public void failed(final exception ex) {
                latch.countdown();
            }
 
            //请求取消后处理
            @override
            public void cancelled() {
                latch.countdown();
            }
 
        });
 
        try {
            latch.await();
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        //关闭
        try {
            client.close();
        } catch (ioexception ignore) {
 
        }
        return resdata[0];
    }
}

3.测试类

package com.ruoyi.test;
 
/**
 * created with idea
 * author:qinwei
 * date:2019/4/10
 * time:10:28
 */
public class mainclass {
 
    /**
     * java回调方法的使用
     * 实际操作时的步骤:(以本实例解释)
     * 1.在回答者的类内创建回调的接口
     * 2.在回答者的类内创建回调接口的对象,
     * 3.在提问者类里面实例化接口对象,重写接口方法
     * 2.-3.这个点很重要,回调对象的实例化,要在提问者的类内实例化,然后重写接口的方法
     * 相当于提问者先把一个联络方式给回答者,回答者找到答案后,通过固定的联络方式,来告诉提问者答案。
     * 4.调用开始新线程的start方法
     * 5.原来的提问者还可以做自己的事
     * */
    public static void main(string[] args) {
        // 小王问小张1+1=?,线程同步
        business xiaozhang = new business();
        int i = xiaozhang.add(1, 1);//回答1+1的答案
 
        // 问小张地球为什么是圆的?回调方法的使用
        //这相当于先定好一个返答案的方式,再来执行实际操作
 
        // 实例化回调接口的对象
        business.calls call = new business.calls() {
            @override
            public void call(string question) {
                //回答问题者,回答后,才能输出答案
                system.err.println(question);
            }
        };
 
        //把回调对象赋值给回答者的回调对象,回答问题者的回调对象才能回答问题
        xiaozhang.calls = call;
 
        system.out.println("吩咐完毕!");
        //相关交代完毕之后再执行查询操作
        xiaozhang.start();
 
        //小王做自己的事!
        system.out.println("处理自己的业务");
    }
}

4.请求结果

总结

1.最好在服务端做一个sleep等待,这样可以更好的模拟效果

2.开启一个子线程去执行请求不影响主线程运行,请求完毕后回调给用户

3.还有很多实现异步回调方式,就不多赘述了

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com