Suck the cat with code! This paper is participating in[Cat Essay Campaign].

preface

This article uses Baidu image-recognition API to realize the identification of animals. Are you still showing off cats for friends but you don’t know the species of embarrassing scene?

process

First use Baidu map recognition API, we need to register the corresponding account

Ai.baidu.com/tech/imager…

After registering, you need to complete your real name authentication and then go to the console to create the app

Did you see it and pick it up? Enter the white piao limit

APIKey and Secret Key are the ones we’ll use later, so we’ll save them in one place

Code

And then start coding

The first step is to obtain the token. This operation class is provided by Baidu official, so we can use it directly without the whole flower

/** * Obtain token class */ public class AuthService {/** * obtain permission token * @return Return example: * {* "access_token": "24.460 da4889caad24cccdb1fea17221975. 2592000.1491995545.282335-1234567," * "expires_in" : 2592000 *} */ public static String getAuth() {clientId = "--------------"; ClientSecret = "--------------"; return getAuth(clientId, clientSecret); } /** * Get the API access token * This token has a certain validity period and needs to be managed by itself, * @param AK - API Key obtained from Baidu cloud * @param sk - Securet Key obtained from Baidu cloud * @return assess_token Example: "*" 24.460 da4889caad24cccdb1fea17221975 2592000.1491995545.282335-1234567 * / public static String getAuth (String ak, String sk) {/ / access token address String authHost = "https://aip.baidubce.com/oauth/2.0/token?"; String getAccessTokenUrl = authHost // 1. Grant_type is a fixed parameter + "grant_type=client_credentials" // 2. API Key + "&client_id=" + ak // 3. Secret Key + "&client_secret=" + sk; try { URL realUrl = new URL(getAccessTokenUrl); HttpURLConnection connection = (HttpURLConnection) realurl.openConnection (); connection.setRequestMethod("GET"); connection.connect(); / / get all the response header field Map < String, a List < String > > Map = connection. GetHeaderFields (); For (String key: map.keyset ()) {system.err.println (key + "-- >" + map.get(key)); } // Define the BufferedReader input stream to read the response to the URL BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) ! = null) { result += line; } / return the result * * * sample * / the e (" TAG ", "getAuth:" + result); JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); return access_token; } catch (Exception e) {system.err.printf (" Failed to obtain token!" ); e.printStackTrace(System.err); } return null; }}Copy the code

The next step, of course, is to create an Activity

Public class SBActivity extends appactivity {private static final int CHOOSE_FILE_CODE = 200; private ImageView mIvSelect; private Button mBtnGetimg; private TextView mTvResult; private String auth; private String param; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sbactivity); initView(); } private void run() {public void run() {auth = new Thread(new Runnable() {@override public void run() {auth = AuthService.getAuth(); } }).start(); // Initialize the layout mIvSelect = findViewById(R.i.iv_select); mBtnGetimg = findViewById(R.id.btn_getimg); mTvResult = findViewById(R.id.tv_result); / / click to start the file manager, mainly for picture mBtnGetimg. The setOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) { mTvResult.setText(""); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*").addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(Intent.createChooser(intent, "Choose File"), CHOOSE_FILE_CODE); } the catch (ActivityNotFoundException e) {Toast. MakeText (SBActivity. This "had no ~ there is ~ ~ ~ is ~", Toast. LENGTH_SHORT), show (); }}}); } @override // after the file is selected, Protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == CHOOSE_FILE_CODE) { if(data! =null){mivSelect.setimageuri (data.getData()); String path = fileutils.getPath (sbactivity.this, data.getData()); Log.e("TAG", "onActivityResult: "+path); // Finally request data through this method sb(path); } } } super.onActivityResult(requestCode, resultCode, data); } private void sb (String path) {/ / request url String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"; Try {// Get the byte stream of the file byte[] bytes = Fileutil. readFileByBytes(path); ImgStr = base64util. encode(bytes); ImgParam = URLEncoder. Encode (imgStr, "utf-8 "); // imgParam =" image=" + imgParam; } catch (Exception e) { e.printStackTrace(); Httputil. setCallBack(new httputil. CallBack() {@override public void call(String data) { @override public void run() {mtvresult.settext (data); }}); }}); Public void run() {try {httputil. post(url, auth, param); } catch (Exception e) { e.printStackTrace(); } } }).start(); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

Okay, a simple animal identification is done, and look at the results

Very nice, old stamp