发送数据
/** * * @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(); } }
接收
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; }
原文:https://www.cnblogs.com/mybug/p/9365607.html