验证码已经是非常常用的反作弊、反攻击手段了,其实要实现这个功能对技术水平好的人也不难,但是并不是每个人,每种语言都天然适合搞某个功能...不过我们可以通过封装接口,来屏蔽差异化,把问题简单化,现在就用一个简单的nodejs脚本来实现验证生成功能,例子如下:
var http = require('http');
var qs = require('querystring');
//配置您申请的appKey和openId
app_key = "***";
open_id = "***";
function request_content(request_url,port,params,method){
var path=request_url;
if(!!params){
var content = qs.stringify(params);
path=request_url+'?' + content;
}
var options = {
port: port,
path: path,
method: method
};
if(method.toLowerCase()=='post'){
options['headers']="Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8";
}
var req = http.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
function main(){
var domain="http://api.xiaocongjisuan.com/";
var port=8080;//http对应80端口,https 对应443端口,请使用者自己改正
var servlet="develop/verificationcode/get";
var method="get";
var request_url=domain+servlet;
var params = {};
params['appKey']=app_key;
params['openId']=open_id;
//变动部分
params["w"]=200;
params["h"]=50;
params["len"]=7;
params["fontSize"]=40;
request_content(request_url,port,params,method);
}
main();
其他语言的实现方式比如php,java,python等可以点这里查看,这里暂且附上比较小众的GO语言的实现方式:
package main
import (
"io/ioutil"
"net/http"
"net/url"
"fmt"
"strings"
)
//配置您申请的appKey和openId
const APP_KEY ="yours";
const OPEN_ID ="yours";
func requestContent(requestUrl string,params url.Values,method string)(rs[]byte ,err error){
if strings.ToUpper(method)=="GET"{
return get(requestUrl,params)
}
return post(requestUrl,params)
}
// get 网络请求
func get(requestUrl string,params url.Values)(rs[]byte ,err error){
var Url *url.URL
Url,err=url.Parse(requestUrl)
if err!=nil{
fmt.Printf("解析url错误:\r\n%v",err)
return nil,err
}
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery=params.Encode()
resp,err:=http.Get(Url.String())
if err!=nil{
fmt.Println("err:",err)
return nil,err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// post 网络请求 ,params 是url.Values类型
func post(requestUrl string, params url.Values)(rs[]byte,err error){
resp,err:=http.PostForm(requestUrl, params)
if err!=nil{
return nil ,err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func main(){
domain :="http://api.xiaocongjisuan.com/"
servlet :="develop/verificationcode/get"
method :="get"
requestUrl:=domain+servlet
//初始化参数
params:=url.Values{}
params.Set("appKey",APP_KEY)
params.Set("openId",OPEN_ID)
//变动部分
params.Set("w","200")
params.Set("h","50")
params.Set("len","7")
params.Set("fontSize","40")
//发送请求
data,err:=requestContent(requestUrl,params,method)
fmt.Println(string(data))
if err!=nil{
fmt.Printf("解析url错误:\r\n%v",err)
}
}