How to generate QR code quickly in Java, python, golang and other development languages?

Time:2020-2-19

There are many ways to generate free QR code! For example, the well-known forage QR code, if it’s just a simple use, it’s enough. But if you want to generate on a large scale, it’s not appropriate. Moreover, many tools are unable to add logo (like wechat QR code) to QR code.

Next, I will talk about how to generate a highly customizable QR code quickly and with high quality.

The coding algorithm of QR code is open, which means that most of the development languages can generate dynamic graphs. But in today’s two-dimensional code application so extensive, still own to build the wheel, if not stupid, that is the true technology geek.

Java has an open-source QR Code Generation Library: com.google.zxing, which is open-source for Android by Google bigwigs. This library is not powerful, but it’s a hole. Who knows
Python is a well-known third-party library. How can two-dimensional code generation be less. For example: myqr, QRcode, etc
Not familiar with other languages, no discussion

Since what I’m talking about is that any development language can generate two-dimensional code, except for the independent implementation of each language. Another solution is to call off the shelf API to generate QR code. It is a good strategy to use API when you want to use it simply, control the development cost or use some minority languages.

Next, I recommend a QR code free API from“Green onion calculation
Detailed description document: https://www.xiaocongjisuan.com/show/api/14

Precautions for API reference:

  • Appkey: unique interface ID, which can be viewed in user background – > Application Center – > My interface
  • Openid: platform ID, which is automatically generated after registration and viewed in user background – > User Center – > account information

Why is this interface recommended? Because only the QR code generated by it can be highly customized, such as logo, color of QR code, background color of QR code, size of QR code, margin, etc. the detailed settings are shown in the following figure:

How to generate QR code quickly in Java, python, golang and other development languages?

There are also some return value descriptions. Please refer to the above API documentation for details! 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);

        //Change part
        Params. Put ("text", "I'm the loveliest guy");
        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
    
    Dictionary of Chinese characters
    params ={}
    params["appKey"]=app_key
    params["openId"]=open_id
    
    #Change part
    Params ["text"] = "I'm the cutest guy"
    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 the 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;
    
    //Change part
    $params ["text"] = "I'm the cutest guy";
    $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 instruction documents in detail. In fact, as long as the post request can be sent, the above method can be used to generate QR code.

The last 2D code legend generated by the above method

How to generate QR code quickly in Java, python, golang and other development languages?