名片识别接口的调用示例
php代码
/*********************************这是请求的参数处理*************************************************/ //示例里面需要导入的包如果你没有,请自行去网上下载,其他异常可留言或在群里提问 import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; import org.apache.commons.codec.binary.Base64; import org.silk.net.PureNetUtil; public class CardAPIDemo { private static final String KEY="****f6e8cda2876336a7f3cd2dcc****";//这里替换成你的key private static final String URL="http://op.juhe.cn/hanvon/bcard/query"; private static final String PATH="D:\\1.jpg";//这里替换成你的图片地址 public static void main(String[] args) { JSONObject obj=JSONObject.fromObject(invoke()); System.out.println("result==>"+obj.getString("result")); } public static String invoke() { Mapparams=new HashMap(); File file=new File(PATH); InputStream in; String html=null; try { in = new FileInputStream(file); int i = in.available(); // 得到文件大小 byte data[] = new byte[i]; in.read(data); // 读数据 in.close(); params.put("key", KEY); Base64 base64=new Base64(true); params.put("image",base64.encodeToString(data));//image参数可不是你的图片地址 html= PureNetUtil.post(URL, params);//这里用到了一个我自己封装的网络请求类,见下文 } catch (Exception e) { e.printStackTrace(); } return html; } } /***********************************这是上面用到的网络请求工具类*************************************/ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class PureNetUtil { /** * 用来输出现在时间 * @return */ public static String currentTime(){ SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制 return sdformat.format(new Date()); } /** * get方法直接调用post方法 * @param url 网络地址 * @return 返回网络数据 */ public static String get(String url){ return post(url,null,null); } public static String get(String url,String charset){ return post(url,null,charset); } /** * 设定post方法获取网络资源,如果参数为null,实际上设定为get方法 * @param url 网络地址 * @param param 请求参数键值对 * @return 返回读取数据 */ public static String post(String url,Mapparam,String outCharset){ if(outCharset==null||outCharset.equals("")){ outCharset="utf-8"; } HttpURLConnection conn=null; try { URL u=new URL(url); conn=(HttpURLConnection) u.openConnection(); conn.setRequestProperty("User-agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.setRequestProperty("Accept", "application/json;charset=utf-8"); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); StringBuffer sb=null; if(param!=null){//如果请求参数不为空 sb=new StringBuffer(); /*A URL connection can be used for input and/or output. Set the DoOutput * flag to true if you intend to use the URL connection for output, * false if not. The default is false.*/ //默认为false,post方法需要写入参数,设定true conn.setRequestMethod("POST"); conn.setDoOutput(true); //设定post方法,默认get //获得输出流 OutputStream out=conn.getOutputStream(); //对输出流封装成高级输出流 BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out)); //将参数封装成键值对的形式 for(Map.Entrys:param.entrySet()){ sb.append(s.getKey()).append("=").append(s.getValue()).append("&"); } System.out.println("para:"+sb.deleteCharAt(sb.toString().length()-1).toString()); writer.write(sb.deleteCharAt(sb.toString().length()-1).toString()); writer.close();//如果忘记关闭输出流将造成参数未完全写入的情况 sb=null; } conn.connect();//建立连接 sb=new StringBuffer(); //获取连接状态码 int recode=conn.getResponseCode(); BufferedReader reader=null; if(recode==404){ } if(recode==200){ //Returns an input stream that reads from this open connection //从连接中获取输入流 InputStream in=conn.getInputStream(); String encoding=conn.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { GZIPInputStream gis = new GZIPInputStream(in); reader=new BufferedReader(new InputStreamReader(gis,outCharset)); for(String str=reader.readLine();str!=null;str=reader.readLine()){ sb.append(str).append(System.getProperty("line.separator"));//原网页的换行加上 } }else{ reader=new BufferedReader(new InputStreamReader(in,outCharset)); for(String str=reader.readLine();str!=null;str=reader.readLine()){ sb.append(str).append(System.getProperty("line.separator"));//原网页的换行加上 } } //关闭输入流 reader.close(); if (sb.toString().length() == 0) { return null; } return sb.toString().substring(0, sb.toString().length() - System.getProperty("line.separator").length()); } } catch (Exception e) { e.printStackTrace(); return null; }finally{ if(conn!=null)//关闭连接 conn.disconnect(); } return null; } public static String post(String url,Mapparam){ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuffer sb=null; try { ListnameValuePairs = new ArrayList(param.size()); if(param!=null){ for(Map.Entry map:param.entrySet()){ nameValuePairs.add(new BasicNameValuePair(map.getKey().toString(), map.getValue().toString())); } } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=httpclient.execute(httppost); InputStream in=response.getEntity().getContent(); sb=new StringBuffer(); BufferedReader reader=new BufferedReader(new InputStreamReader(in)); for(String str=reader.readLine();str!=null;str=reader.readLine()){ sb.append(str).append(System.getProperty("line.separator"));//原网页的换行加上 } reader.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } /** * 这个方法主要是用来直接向服务器传输参数,比如已经加密的数据,直接传到服务器 * @param url * @param data * @return */ public static String post(String url,byte[] data ){ HttpURLConnection conn=null; try { URL u=new URL(url); conn=(HttpURLConnection) u.openConnection(); conn.setRequestProperty("User-agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"); StringBuffer sb=null; sb=new StringBuffer(); /*A URL connection can be used for input and/or output. Set the DoOutput * flag to true if you intend to use the URL connection for output, * false if not. The default is false.*/ //默认为false,post方法需要写入参数,设定true conn.setRequestMethod("POST"); conn.setDoOutput(true); //设定post方法,默认get //获得输出流 OutputStream out=conn.getOutputStream(); //对输出流封装成高级输出流 BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out)); //将参数封装成键值对的形式 writer.write(new String(data)); writer.close();//如果忘记关闭输出流将造成参数未完全写入的情况 conn.connect();//建立连接 //获取连接状态码 int recode=conn.getResponseCode(); BufferedReader reader=null; if(recode==404){ System.out.println("404===>"+url); } if(recode==200){ //Returns an input stream that reads from this open connection //从连接中获取输入流 InputStream in=conn.getInputStream(); String encoding=conn.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { GZIPInputStream gis = new GZIPInputStream(in); reader=new BufferedReader(new InputStreamReader(gis)); for(String str=reader.readLine();str!=null;str=reader.readLine()){ sb.append(str).append(System.getProperty("line.separator"));//原网页的换行加上 } }else{ reader=new BufferedReader(new InputStreamReader(in)); for(String str=reader.readLine();str!=null;str=reader.readLine()){ sb.append(str).append(System.getProperty("line.separator"));//原网页的换行加上 } } //关闭输入流 reader.close(); if (sb.toString().length() == 0) { return null; } return sb.toString().substring(0, sb.toString().length() - System.getProperty("line.separator").length()); } } catch (Exception e) { e.printStackTrace(); return null; }finally{ if(conn!=null)//关闭连接 conn.disconnect(); } return null; } }
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전
By 尊渡假赌尊渡假赌尊渡假赌
어 ass 신 크리드 그림자 : 조개 수수께끼 솔루션
2 몇 주 전
By DDD
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전
By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7530
15


Cakephp 튜토리얼
1378
52


Steam의 계정 이름 형식은 무엇입니까?
82
11


Win11 활성화 키 영구
54
19


NYT 연결 힌트와 답변
21
76

