222
PackageApplication;Importjava.io.IOException;ImportJava.net.URL;ImportJava.util.ResourceBundle;ImportCom.google.gson.Gson;Importjavafx.event.ActionEvent;ImportJavafx.fxml.FXML;Importjavafx.fxml.Initializable;ImportJavafx.scene.control.Button;ImportJavafx.scene.control.TextArea;ImportJavafx.scene.control.TextField;ImportOKHTTP3. okhttpclient;ImportOKHTTP3. Request;ImportOKHTTP3. Response; Public classControllerImplementsinitializable{@FXMLPrivatebutton button; @FXMLPrivateTextField TextField; @FXMLPrivateTextArea TextArea; Private StaticOkhttpclient client =Newokhttpclient (); //initiating a request to get content Public StaticString Getjson (string url)throwsIOException {Request Request=Newrequest.builder (). URL (URL). build (); Response Response=Client.newcall (Request). Execute (); returnresponse.body (). String (); } //The function calls the API and uses Gson to parse the JSON data to get the key Public Staticstring Getkey (String corpid,string corpsecret) {string JSON=NULL; Try{JSON= Getjson ("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +corpid+ "&corpsecret=" +Corpsecret); }Catch(Exception e) {e.printstacktrace (); } Gson Gson=NewGson (); Weixinapi Wxapi= Gson.fromjson (JSON, WEIXINAPI.class); returnWxapi.getaccess_token (); } //The function calls the API and uses Gson to parse the JSON data to get the user ID Public Staticstring[] GetID (string token,string Xuehao) {string JSON=NULL; Try{JSON= Getjson ("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" +token+ "&userid=" +Xuehao); }Catch(Exception e) {e.printstacktrace (); } System.out.println (JSON); if(Json.contains ("OK") {Gson Gson=NewGson (); Idapi Iapi= Gson.fromjson (JSON, IDAPI.class); String XB=NULL; if(Iapi.getgender (). Equals ("1") ) {XB= "Male"; }Else if(Iapi.getgender (). Equals ("2") ) {XB= "female"; } return Newstring[]{"School Number:" +Iapi.getuserid (),"Name:" +iapi.getname (),"Phone Number:" +iapi.getmobile (),"Gender:" +XB,"No.:" +Iapi.getweixinid ()}; }Else { return Newstring[]{"User not find", };} } @FXMLPrivate voidhandlebuttonaction (ActionEvent event) {String key=getkey ("Test", "test"); String Xuehao=Textfield.gettext (); for(String Str:getid (Key,xuehao)) {Textarea.appendtext (str+ "\ n"); }} @Override Public voidInitialize (URL arg0, ResourceBundle arg1) {//TODO auto-generated Method Stub } }
The Okhttp/gson2 of basic learning in JavaFX