二维码生成,打包下载zip,BigDecimal的取值和计算,java发送http请求

      最近工作中用到不少知识点之前经常拿来用,但大都是不求甚解,现在将几个知识点都一起总结一下与大家分享。

一、生成二维码

      公司有业务要批量生成设备二维码供用户进行扫码绑定,遂写了一个根据所需要携带的信息生成二维码的方法。

Hashtable hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 2);

BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height + 100, BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.getGraphics();
Graphics2D g2d = (Graphics2D) graphics;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, width, height + 100);
for (int x = 0; x < width; x++) {
  for (int y = 0; y < height; y++) {
  image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
  }
}

g2d.setColor(Color.BLACK);
g2d.setFont(new Font("宋体", Font.BOLD, 26));
int left = 25;
int top = 360;
int rowOffset = 35;
String content = "this is content";
g2d.drawString(content, left, top);
g2d.dispose();
image.flush();

ByteArrayOutputStream ost = new ByteArrayOutputStream();
ImageIO.write(image, "png", ost);
复制代码

      上面是通过content不同的内容插入到二维码之中,生成对应的二维码图片。

二、打包下载ZIP

      生成二维码之后的业务需求就是在要紧接着将刚才生成的二维码们进行批量下载,这时就需要进行打包成ZIP压缩包。

List keys = new ArrayList();
String eachKey;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(baos);
Storage bkt = Storage.bucket("device/keys");//OSS路径
byte[] data;
for (int i = 0; i < keys.size(); i++) {
  eachKey = keys.get(i);
  //获取每一个文件
  out.putNextEntry(new ZipEntry("key" + eachKey + ".png"));
  out.setEncoding("UTF-8");
  String name = "/model/" + eachKey +".png";
  if (bkt.exist(name)) {
     data = bkt.get(name);
     out.write(data);
  }
  out.closeEntry();
}
out.flush();
out.close();
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
bos.write(baos.toByteArray());
复制代码

      以上就是先通过ByteArrayOutputStream依次往里面添加每一个OSS上面存在的key的png文件,最后通过response的输出流将所需文件进行打包返回。

三、BigDecimal的取值和计算

      由于float和double类型的主要设计目标是为了科学计算和工程计算,但是在精准的计算结果上表现却不能达到要求,这时就需要BigDecimal派上用场了。

1、构造方法

      (1).public BigDecimal(double val)    将double表示形式转换为BigDecimal *不建议使用

      (2).public BigDecimal(int val)      将int表示形式转换成BigDecimal

      (3).public BigDecimal(String val)  将String表示形式转换成BigDecimal *建议使用

2、加减乘除

 BigDecimal a = new BigDecimal("4.5");
 BigDecimal b = new BigDecimal("1.5");

 System.out.println("a + b =" + a.add(b));
 System.out.println("a - b =" + a.subtract(b));
 System.out.println("a * b =" + a.multiply(b));
 System.out.println("a / b =" + a.divide(b));
复制代码

3、取值

      divide(BigDecimal divisor, int scale, int roundingMode) 第一参数表示除数, 第二个参数表示小数点后保留位数, 第三个参数表示舍入模式,只有在作除法运算或四舍五入时才用到舍入模式,有下面这几种

ROUND_CEILING    //向正无穷方向舍入

ROUND_DOWN    //向零方向舍入

ROUND_FLOOR    //向负无穷方向舍入

ROUND_HALF_DOWN    //向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入, 例如1.55 保留一位小数结果为1.5

ROUND_HALF_EVEN    //向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,如果保留位数是奇数,使用ROUND_HALF_UP,如果是偶数,使用ROUND_HALF_DOWN

ROUND_HALF_UP    //向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向上舍入, 1.55保留一位小数结果为1.6

ROUND_UNNECESSARY    //计算结果是精确的,不需要舍入模式

ROUND_UP    //向远离0的方向舍入
复制代码

4、注意事项

      减乘除其实最终都返回的是一个新的BigDecimal对象,因为BigInteger与BigDecimal都是不可变的(immutable)的,在进行每一步运算时,都会产生一个新的对象。

BigDecimal a = new BigDecimal("4.5");
BigDecimal b = new BigDecimal("1.5");
a.add(b);
System.out.println(a);  //输出4.5 原来的a不变,加减乘除方法会返回一个新的BigDecimal对象,需要保存计算后的值,
复制代码

四、Java发起http请求

      因为在一些接口处理过程当中需要调用别的接口api获取的数据,所以需要从java自身发起http请求来获取数据,一般java原生的HttpURLConnection就已经够用,如下

1、get请求

 HttpURLConnection connection = null;
 InputStream is = null;
 BufferedReader br = null;
 String result = null;// 返回结果字符串
 String urlPath = "";
 try {
      // 创建远程url连接对象
      URL url = new URL(urlPath);
      // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
      connection = (HttpURLConnection) url.openConnection();
      // 设置连接方式:get
      connection.setRequestMethod("GET");
      // 设置连接主机服务器的超时时间:15000毫秒
      connection.setConnectTimeout(15000);
      // 设置读取远程返回的数据时间:60000毫秒
      connection.setReadTimeout(60000);
      // 发送请求
      connection.connect();
      // 通过connection连接,获取输入流
      if (connection.getResponseCode() == 200) {
          is = connection.getInputStream();
          // 封装输入流is,并指定字符集
          br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
          // 存放数据
          StringBuffer sbf = new StringBuffer();
          String temp;
          while ((temp = br.readLine()) != null) {
              sbf.append(temp);
              sbf.append("\r\n");
          }
          result = sbf.toString();
      }
  } catch (MalformedURLException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  } finally {
      // 关闭资源
      if (null != br) {
          try {
              br.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      
      if (null != is) {
          try {
              is.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      connection.disconnect();// 关闭远程连接
  }
复制代码

2、post请求

 HttpURLConnection connection = null;
 InputStream is = null;
 OutputStream os = null;
 BufferedReader br = null;
 String result = null;
 String param = "";
 String uslPath = "";
 try {
      URL url = new URL(uslPath);
      // 通过远程url连接对象打开连接
      connection = (HttpURLConnection) url.openConnection();
      // 设置连接请求方式
      connection.setRequestMethod("POST");
      // 设置连接主机服务器超时时间:15000毫秒
      connection.setConnectTimeout(15000);
      // 设置读取主机服务器返回数据超时时间:60000毫秒
      connection.setReadTimeout(60000);
       
      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setDoOutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setDoInput(true);
      // 设置通用的请求属性
      // 如果Content-Type是x-www-form-urlencoded,param则应该是name1=value1&name2=value2格式
      // 如果Content-Type是application/json,param则应该是json格式
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      // 通过连接对象获取一个输出流
      os = connection.getOutputStream();
      // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
      os.write(param.getBytes());
      // 通过连接对象获取一个输入流,向远程读取
      if (connection.getResponseCode() == 200) {
           is = connection.getInputStream();
           // 对输入流对象进行包装:charset根据工作项目组的要求来设置
           br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
           StringBuffer sbf = new StringBuffer();
           String temp = null;
           // 循环遍历一行一行读取数据
           while ((temp = br.readLine()) != null) {
               sbf.append(temp);
               sbf.append("\r\n");
           }
           result = sbf.toString();
           }
   } catch (MalformedURLException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   } finally {
       // 关闭资源
       if (null != br) {
           try {
               br.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       if (null != os) {
           try {
               os.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
           if (null != is) {
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       // 断开与远程地址url的连接
       connection.disconnect();
   }
复制代码

转载于:https://juejin.im/post/5bd550f46fb9a05ce95ca62d

你可能感兴趣的:(java,json)