How can java, python, golang and other development languages generate two-dimensional codes quickly?

Posted by artacus on Sun, 13 Oct 2019 07:07:05 +0200

There are many ways to generate free two-dimensional codes! For example, the famous two-dimensional code for forage is enough if it is used simply. But if you want to generate on a large scale, it's not appropriate. Moreover, many tools can't add logo to the two-dimensional code (just like the two-dimensional code of Wechat).

Next, I'll talk about how to generate a highly customizable two-dimensional code quickly and with high quality.

The encoding algorithm of two-dimensional codes is open, which means that most development languages can generate motion pictures. But in today's world where two-dimensional codes are so widely used, it's a real geek to build wheels by himself, if not foolishly.

Java has an open source two-dimensional code generation library: com.google.zxing, which is open source for android by Google. This library can not be said to be weak, but the pit is pressing, who knows with it?
python is a well-known third-party library, and how little is it for two-dimensional code generation? For example: myqr, qrcode, etc.
Other languages are not familiar with, do not discuss.

Since what I'm talking about is that any development language can generate two-dimensional codes, except that each language can be implemented independently. Another solution is to call existing APIs to generate two-dimensional codes. API is a good strategy for situations where you want to use it simply, control development costs, or use minority languages.

Next I recommend a two-dimensional code generated API free of charge, from "Shallot Computing"
Detailed documentation: https://www.xiaocongjisuan.com/show/api/14

API Reference Notes:

  • appKey: Unique ID of the interface, in the user background - > Application Center - > My interface view
  • openId: Platform id, automatically generated after registration, in the user background - > User Center - > account information view

Why recommend this interface? Because only the two-dimensional codes generated by it can be highly customized, such as logo, color of two-dimensional codes, background color of two-dimensional codes, size of two-dimensional codes, margin and so on. Detailed settings are as follows:

There are also some instructions for return values, refer to the api instructions above. Next, I will post some common development languages using DEMO.

java version:

package com.xiaocongjisuan.module.example;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class Application {
    
     public static final String DEF_CHATSET = "UTF-8";
     public static final int DEF_CONN_TIMEOUT = 30000;
     public static final int DEF_READ_TIMEOUT = 30000;
     public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
     
     //Configure the appKey and openId you applied for
     public static final String APP_KEY ="yours";
     public static final String OPEN_ID ="yours";
     
     //Change map type to request parameter type
     public static String urlEncode(Map<String,Object> params) {
        
        if(params==null){return "";};
         
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String,Object> i : params.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String r=sb.toString();
        if(r.endsWith("&")){
            r = r.substring(0,r.length()-1);
        }
        return r;
     }
     
     /**
     *
     * @param requestUrl Request address
     * @param params Request parameters
     * @param method Request method
     * @return Request result
     * @throws Exception
     */
     public static String requestContent(String requestUrl, Map<String,Object> params,String method) throws Exception {
        
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {

            //Assembly request link
            StringBuffer sb = new StringBuffer();
            
            if(method!=null&&method.equalsIgnoreCase("get")){
                requestUrl = requestUrl+"?"+urlEncode(params);
            }

            //Default get
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            
            if(method!=null&&method.equalsIgnoreCase("post")){
                 conn.setRequestMethod("POST");
                 conn.setDoOutput(true);
                 conn.setDoInput(true);
            }

            //Parameter configuration
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            
            if (params!= null && method.equalsIgnoreCase("post")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlEncode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            //Read data
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
    
    
    public static void main(String[] args) throws Exception{
        
        String domain="http://api.xiaocongjisuan.com/";
        String servlet="develop/qrcode/create";
        String method="get";
        
        String requestUrl=domain+servlet;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("appKey",APP_KEY);
        params.put("openId",OPEN_ID);

        //Variable part
        params.put("text","I'm the cutest boy.");
        params.put("w",400);
        params.put("m",1);
        params.put("color","000000");
        params.put("bgColor","ffffff");
        
        String result=requestContent(requestUrl,params,method);
        System.out.println(result);
    }
}

python version

# -*- coding: utf-8 -*-
# flake8: noqa
__author__ = 'wukong'

import urllib
from urllib import urlencode

#Configure the appKey and openId you applied for
app_key="***"
open_id="***"

"""
request_url Request address
params Request parameters
method Request method

"""
def request_content(request_url,params,method):
    params = urlencode(params)
    
    if method and method.lower() =="get":
        f = urllib.urlopen("%s?%s" % (request_url, params))
    else:
        f = urllib.urlopen(request_url, params)
 
    content = f.read()
    print content

   
def main():
    
    domain="http://api.xiaocongjisuan.com/";
    servlet="develop/qrcode/create"
    method="get"
    request_url=domain+servlet
    
    #Dictionaries
    params ={}
    params["appKey"]=app_key
    params["openId"]=open_id
    
    #Variable part
    params["text"]="I'm the cutest boy."
    params["w"]=400
    params["m"]=1
    params["color"]="000000"
    params["bgColor"]="ffffff"
    
    request_content(request_url,params,method)
    
if __name__ == '__main__':
    main()

php version:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<?php

/**
 * @author 
 * @copyright 2019
 */
 
header("content-type:text/html;charset=utf-8");         //Set encoding
 
//Configure the appKey and openId you applied for
$app_key = "***";
$open_id = "***";

/**
$url Request address
$params Request parameters
$ispost Request method
*/

function http_curl($url,$params=false,$ispost=false){
   
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , "xiaocongjisuan");
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    
    return $response;
}

function main(){
    
    global $app_key;
    global $open_id;
    
    $domain="http://api.xiaocongjisuan.com/";
    $servlet="develop/qrcode/create";
    $method="get";
    
    $url=$domain."".$servlet;
    
    $params['appKey']=$app_key;
    $params['openId']=$open_id;
    
    //Variable part
    $params["text"]="I'm the cutest boy.";
    $params["w"]=400;
    $params["m"]=1;
    $params["color"]="000000";
    $params["bgColor"]="ffffff";
    
    //Code conversion
    foreach ($params as $key=>$value) {
        $params[$key]=mb_convert_encoding($value, "UTF-8", "GBK");
    }

    $paramstring = http_build_query($params);
    $content = http_curl($url,$paramstring,true);
    
    return $content;
}

echo main();
?>

For other languages, you can view the instructions in detail. In fact, as long as POST requests can be sent, two-dimensional codes can be generated using the above method.

The last two-dimensional code legend generated by the above method

Topics: Java QRCode encoding Google