0 概述
在写app后台的时候,需要调用另一个服务器上的算法服务,所以需要发送http请求来获取结果。
考虑到一个功能(比如智能中医)需要调用好几个接口(人脸识别,舌苔识别,饮食推荐),大部分时间花在等待接口的处理上,如果一个接一个地调用,耗时比较长。
所以使用多线程来处理这几个接口调用,以此减少消耗时间。(在发送一个请求后不盲等,继续发送另一个请求,这相当于一种异步请求)
1 post请求
/** * * @param url:http接口地址 * @param param:传入参数,格式为?param1=xxx¶m2=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()) { }