發送數據java
/** * * @param httpUrl * @param param */ public static void postSend(String httpUrl,String param){ try{ URL url = new URL(httpUrl); SslUtils.ignoreSsl(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("connection", "keep-alive"); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); connection.setUseCaches(false); //post請求 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); String json = param.toString(); out.write(param.toCharArray(),0,param.length()); System.out.println(json); out.flush(); out.close(); // 讀取響應 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sb.append(lines); } JSONObject jsStr =JSONObject.parseObject(sb.toString()); //獲取響應值,判斷是否驗證經過 String code = (String) jsStr.get("code"); String msg=(String) jsStr.get("msg"); System.out.println("code:"+code+",msg:"+msg); String result = null; //接口返回驗證數據是否經過 if("0".equals(code)){ result = "success"; } else{ result = "fail"; System.out.println("下發出錯:錯誤緣由爲" + msg + "下發內容爲:" + json); } reader.close(); // 斷開鏈接 connection.disconnect(); }catch(Exception e){ e.printStackTrace(); } }
接收json
String param = accept(request);數組
public static String accept(HttpServletRequest request){ // 接收傳過來的參數 BufferedInputStream bufferedInputStream = null; // 此類實現了一個輸出流,其中的數據被寫入一個字節數組 ByteArrayOutputStream bytesOutputStream = null; String result = null; try { // BufferedInputStream 輸入流 bufferedInputStream = new BufferedInputStream (request.getInputStream ()); bytesOutputStream = new ByteArrayOutputStream(); // 寫入數據 int ch; while ((ch = bufferedInputStream.read ()) != -1) { bytesOutputStream.write (ch); } // 轉換爲String類型 result = new String (bytesOutputStream.toByteArray (),"UTF-8"); }catch (Exception ex){ ex.printStackTrace (); } return result; }