zoukankan      html  css  js  c++  java
  • java发送http请求和多线程

    0 概述

    在写app后台的时候,需要调用另一个服务器上的算法服务,所以需要发送http请求来获取结果。

    考虑到一个功能(比如智能中医)需要调用好几个接口(人脸识别,舌苔识别,饮食推荐),大部分时间花在等待接口的处理上,如果一个接一个地调用,耗时比较长。

    所以使用多线程来处理这几个接口调用,以此减少消耗时间。(在发送一个请求后不盲等,继续发送另一个请求,这相当于一种异步请求)

    1 post请求

    /**
     * 
     * @param url:http接口地址
     * @param param:传入参数,格式为?param1=xxx&param2=xxx,如果值xxx含有特殊字符,可以用param = "image=" + URLEncoder.encode(image,"utf-8");
     * @return: 返回调用接口得到的json字符串(是否为json字符串决定于http接口),是json字符串则可以进行相应解析,Map<String,Object> moodRes = (Map<String,Object>)JSONObject.parse(result)
     * @throws Exception
     */
    public static String postRequest(String url, String param) throws Exception{
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("POST");
                
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
           
        } catch (Exception e) {
            throw e;
        }finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    2 get请求

    public static String getRequest(String url) throws Exception{
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection)urlGet.openConnection();
            http.setRequestMethod("GET"); 
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
    
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
    
            http.connect();
    
            InputStream is = http.getInputStream();
            int size = is.available();
                
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8"); 
    
            is.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    3 json解析

    http请求得到的一般是json格式的字符串,利用json包解析成需要的结果,不同json包解析方法有所不同。

    import net.sf.json.JSONObject;
    JSONObject jsonObj = JSONObject.fromObject(jsonStr);
    String res1 = jsonObj.getString("key1");
    int res2 = jsonObj.getInt("key2");
    
    //////////////////////////////////////////////////////////////////////////////////
    
    import com.alibaba.fastjson.JSONObject;
    Map<String,Object> jsonObj = (Map<String,Object>)JSONObject.parse(jsonStr);
    String res1 = (String)jsonObj.get("key1");
    int res2 = (Integer)jsonObj.get("key2");

    4 多线程

    //用线程池发送请求
    ExecutorService executor = Executors.newFixedThreadPool(3);
    //问诊 Question taskForQuestion = new Question(symptom); Thread t1 = new Thread(taskForQuestion); executor.execute(t1); //人脸望诊 taskForFace = new LookForFace(facePath); Thread t2 = new Thread(taskForFace); executor.execute(t2); //舌苔望诊 taskForTongue = new LookForTongue(tonguePath); Thread t3 = new Thread(taskForTongue); executor.execute(t3); //等待线程执行完毕,每一个task都发送了请求并获取结果解析后放到task中的某个变量中,执行完后就可以获得这些变量来获得所要的结果 executor.shutdown(); while(!executor.isTerminated()) { }
  • 相关阅读:
    使用littleTools简化docker/kubectl的命令
    (上)python3 selenium3 从框架实现学习selenium让你事半功倍
    一篇文教你使用python Turtle库画出“精美碎花小清新风格树”快来拿代码!
    VxLAN协议详解
    深入理解大数据之——事务及其ACID特性
    深入理解大数据架构之——Lambda架构
    JQCloud: 一个前端生成美化标签云的简单JQuery插件
    详解Java中的final关键字
    OpenDaylight虚拟租户网络(VTN)详解及开发环境搭建
    使用Pelican在Github(国外线路访问)和Coding(国内线路访问)同步托管博客
  • 原文地址:https://www.cnblogs.com/liaohuiqiang/p/7627022.html
Copyright © 2011-2022 走看看