首页 > 代码库 > JavaFX基础学习之OkHttp/Gson
JavaFX基础学习之OkHttp/Gson
导入jar包,使用OkHttp/Okio/Gson请求解析
package application; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import com.google.gson.Gson; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Controller implements Initializable{ @FXML private Button button; @FXML private TextField textfield; @FXML private TextArea textarea; private static OkHttpClient client = new OkHttpClient(); //发起请求,获取内容 public static String getjson (String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } //函数调用api,并利用gson解析json数据 public static String getdata(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 = new Gson(); weixinapi wxapi = gson.fromJson(json, weixinapi.class); return wxapi.getAccess_token(); } @FXML private void handleButtonAction(ActionEvent event) { String key=getdata("test","test"); textarea.appendText(key); } @Override public void initialize(URL arg0, ResourceBundle arg1) { // TODO Auto-generated method stub } }
JavaFX基础学习之OkHttp/Gson
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。