1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 图形验证码识别接口()

图形验证码识别接口()

时间:2018-10-05 13:01:13

相关推荐

图形验证码识别接口()

一、效果演示:/imgcode/demo.html

本地图片识别

网络图片识别

二、免费api接口

接口地址:/imgcode/

请求类型:post

接口参数:

返回数据:

数据格式:json

python实现

# -*- coding: utf-8 -*-# @Date : /10/03# @Author : 薄荷你玩# @Website :import jsonimport requestsTOKEN = 'free' # token 获取:/imgcode/gettokenURL = '/imgcode/' # 接口地址def imgcode_online(imgurl):"""在线图片识别:param imgurl: 在线图片网址 / 图片base64编码(包含头部信息):return: 识别结果"""data = {'token': TOKEN,'type': 'online','uri': imgurl}response = requests.post(URL, data=data)print(response.text)result = json.loads(response.text)if result['code'] == 200:print(result['data'])return result['data']else:print(result['msg'])return 'error'def imgcode_local(imgpath):"""本地图片识别:param imgpath: 本地图片路径:return: 识别结果"""data = {'token': TOKEN,'type': 'local'}# binary上传文件files = {'file': open(imgpath, 'rb')}response = requests.post(URL, files=files, data=data)print(response.text)result = json.loads(response.text)if result['code'] == 200:print(result['data'])return result['data']else:print(result['msg'])return 'error'if __name__ == '__main__':imgcode_online('/test.png')imgcode_local('img/test.png')# 输出样例:# {'code': 200, 'msg': 'ok', 'data': '74689'}# 74689

Java实现

/*** @author 薄荷你玩* @date /10/04* @Website */import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import .HttpURLConnection;import .URL;import .URLEncoder;import java.nio.charset.StandardCharsets;import java.util.*;import java.util.Map.Entry;import javax.imageio.ImageIO;import javax.imageio.stream.ImageInputStream;public class ImgcodeUtil {private static final String URL = "/imgcode/"; //接口地址private static final String TOKEN = "free"; // token 获取:/imgcode/gettokenprivate final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识private final static String PREFIX = "--";// 必须存在private final static String LINE_END = "\r\n";/*** 网络图片识别** @param imgUrl 图片网址/图片base64编码* @return 服务器返回结果(json格式)*/private static String imgcode_online(String imgUrl) {String BOUNDARY = UUID.randomUUID().toString(); // 文件边界随机生成HttpURLConnection con = null;BufferedReader buffer = null;StringBuffer resultBuffer = null;try {URL url = new URL(URL);//得到连接对象con = (HttpURLConnection) url.openConnection();//设置请求类型con.setRequestMethod("POST");//设置请求需要返回的数据类型和字符集类型con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//允许写出con.setDoOutput(true);//允许读入con.setDoInput(true);//不使用缓存con.setUseCaches(false);DataOutputStream out = new DataOutputStream(con.getOutputStream());String content = "token=" + TOKEN;content += "&type=online";content += "&uri=" + URLEncoder.encode(imgUrl);// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面out.writeBytes(content);out.flush();out.close();//得到响应码int responseCode = con.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {//得到响应流InputStream inputStream = con.getInputStream();//将响应流转换成字符串resultBuffer = new StringBuffer();String line;buffer = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));while ((line = buffer.readLine()) != null) {resultBuffer.append(line);}return resultBuffer.toString();}} catch (Exception e) {e.printStackTrace();}return "";}/*** 本地图片上传** @param path 图片路径* @return 返回数据(json)*/public static String imgcode_local(String path) throws Exception {HttpURLConnection conn = null;InputStream input = null;OutputStream os = null;BufferedReader br = null;StringBuffer buffer = null;try {URL url = new URL(URL);conn = (HttpURLConnection) url.openConnection();conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setConnectTimeout(1000 * 10);conn.setReadTimeout(1000 * 10);conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);conn.connect();// 往服务器端写内容 也就是发起http请求需要带的参数os = new DataOutputStream(conn.getOutputStream());// 请求参数部分Map requestText = new HashMap();requestText.put("token", TOKEN);requestText.put("type", "local");writeParams(requestText, os);// 请求上传文件部分writeFile(path, os);// 请求结束标志String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;os.write(endTarget.getBytes());os.flush();// 读取服务器端返回的内容if (conn.getResponseCode() == 200) {input = conn.getInputStream();} else {input = conn.getErrorStream();}br = new BufferedReader(new InputStreamReader(input, "UTF-8"));buffer = new StringBuffer();String line = null;while ((line = br.readLine()) != null) {buffer.append(line);}} catch (Exception e) {throw new Exception(e);} finally {try {if (conn != null) {conn.disconnect();conn = null;}if (os != null) {os.close();os = null;}if (br != null) {br.close();br = null;}} catch (IOException ex) {throw new Exception(ex);}}return buffer.toString();}/*** 对post参数进行编码处理并写入数据流中** @throws Exception* @throws IOException*/private static void writeParams(Map requestText, OutputStream os) throws Exception {try {StringBuilder requestParams = new StringBuilder();Set set = requestText.entrySet();Iterator it = set.iterator();while (it.hasNext()) {Entry entry = (Entry) it.next();requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);requestParams.append("Content-Type: text/plain; charset=utf-8").append(LINE_END);requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容requestParams.append(entry.getValue());requestParams.append(LINE_END);}os.write(requestParams.toString().getBytes());os.flush();} catch (Exception e) {throw new Exception(e);}}/*** 对post上传的文件进行编码处理并写入数据流中** @throws IOException* @path 文件路径*/private static void writeFile(String path, OutputStream os) throws Exception {try {InputStream is = null;File file = new File(path);StringBuilder requestParams = new StringBuilder();requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);requestParams.append("Content-Disposition: form-data; name=\"").append("file").append("\"; filename=\"").append(file.getName()).append("\"").append(LINE_END);requestParams.append("Content-Type:").append(getContentType(file)).append(LINE_END);requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容os.write(requestParams.toString().getBytes());is = new FileInputStream(file);byte[] buffer = new byte[1024 * 1024];int len = 0;while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);}os.write(LINE_END.getBytes());os.flush();} catch (Exception e) {throw new Exception(e);}}/*** 获取ContentType*/public static String getContentType(File file) throws Exception {String streamContentType = "application/octet-stream";String imageContentType = "";ImageInputStream image = null;try {image = ImageIO.createImageInputStream(file);if (image == null) {return streamContentType;}Iterator it = ImageIO.getImageReaders(image);if (it.hasNext()) {imageContentType = "image/png";return imageContentType;}} catch (IOException e) {throw new Exception(e);} finally {try {if (image != null) {image.close();}} catch (IOException e) {throw new Exception(e);}}return streamContentType;}public static void main(String[] args) throws Exception {String path = "E:\\NLP_study\\imgcode\\img\\test.png";System.out.println(imgcode_local(path));System.out.println(imgcode_online("/test.png"));// 输出:// {"code":200,"msg":"ok","times":93,"data":"yemm"}// {"code":200,"msg":"ok","times":92,"data":"74689"}}}

HTML/JavaScript实现

网络图片识别:

<!--网络图片识别/html--><input type="text" name="uri" id="uri" placeholder="请输入验证码图片网址" /><input type="button" onclick="imgcode()" value="识别" /><input name="token" id="token" value="free" type="hidden"><input name="type" value="online" type="hidden"><p>识别结果:<span id="resultCode" style="color:red;">请稍后...</span></p>

// 网络图片识别/jsfunction imgcode() {if ($("#uri").val() == "") {alert("网址不能为空");return;}$.ajax({type: "post",url: "/imgcode/",data: {token: $("#token").val(),uri: $("#uri").val(),type: "online"},dataType: "json",success: function (data) {console.log(data);if (data.code > 0) {$("#resultCode").text(data.data);} else {$("#resultCode").text(data.msg);}},error: function (result) {console.log(result);$("#resultCode").text(JSON.stringify(result));alert("系统繁忙,请稍后再试!");}});}

本地图片上传:

<!--本地图片上传/html--><form encType="multipart/form-data" method="post" id="selPicture"><input type="file" accept="image/*" name="selPicture" id="file" /><input type="button" name="upload" onclick="sendimg()" id="upload" value="识别" /><input name="token" value="free" type="hidden"><input name="type" value="local" type="hidden"></form><p>识别结果:<span id="resultCode" style="color:red;">请稍后...</span></p>

// 本地图片上传/jsfunction sendimg() {var $file1 = $("input[name='selPicture']").val();//用户文件内容(文件)// 判断文件是否为空if ($file1 == "") {alert("请选择上传的目标文件! ")return false;}//判断文件大小var size1 = $("input[name='selPicture']")[0].files[0].size;if (size1 > 5242880) {alert("上传文件不能大于5M!");return false;}boo1 = true;var type = "file";var formData = new FormData($("#selPicture")[0]);//这里需要实例化一个FormData来进行文件上传$.ajax({type: "post",url: "/imgcode/",data: formData,processData: false,contentType: false,dataType: "json",success: function (data) {console.log(data);if (data.code == 200) {$("#resultCode").text(data.data);} else {$("#resultCode").text(data.msg);}},error: function (result) {console.log(result);$("#resultCode").text(JSON.stringify(result));alert("系统繁忙,请稍后再试!");}});}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。