http請求和多線程
阿新 • • 發佈:2017-10-04
服務 xxx encode static 解析 con 決定 writer json字符串
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()) { }
http請求和多線程