javafx 五、网络请求

添加jar包

去mave仓库中下载jar包
注意:okio包要下载1版本的,2版本的会报错,有个类找不到
javafx 五、网络请求_第1张图片

封装网络请求

package sample.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.Map;

public class HttpUtil {

    private static String PrefixURL = "xxx"; //  //
    public static String uri_login="xxx";

    private final OkHttpClient mOkHttpClient;
    private volatile static HttpUtil INSTANCE;

    public HttpUtil() {
        mOkHttpClient = new OkHttpClient();
    }

    public static HttpUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpUtil();
                }
            }
        }
        return INSTANCE;
    }

    public void get(String json,String uri,HttpCallBack callBack){
        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json; charset=utf-8")
                .url(PrefixURL + uri)
                .get().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("IOException>>"+e.toString());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                System.out.println("response>>"+response.body());
            }
        });
    }

    public void post(Map map, String uri, HttpCallBack callBack){

        FormBody.Builder builder = new FormBody.Builder();
        for (String in : map.keySet()) {
            builder.add(in, map.get(in));
        }
        RequestBody body = builder.build();

        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json; charset=utf-8")
                .url(PrefixURL + uri)
                .post(body).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                boolean successful = response.isSuccessful();
                if(successful){
//                    callBack.success(response.body().string());
                    String success = response.body().string();
                    JSONObject jsonObject=JSONObject.parseObject(success);
                    Boolean aBoolean = jsonObject.getBoolean("success");
                    if(aBoolean){
                        JSONObject data = jsonObject.getJSONObject("data");
                        callBack.success(data.toJSONString());
                    }else{
                        String message = jsonObject.getString("message");
                        if(StringUtil.isEmpty(message)){
                            callBack.fail("请求失败");
                        }else{
                            callBack.fail(message);
                        }
                    }
                }else{
                    callBack.fail("请求失败");
                }
            }
        });
    }
}

请求回调

package sample.utils;

public interface HttpCallBack {
    void success(String success);
    void fail(String fail);
}

调用网络请求

  HashMap hashMap=new HashMap<>();
        hashMap.put("username",userNameText);
        hashMap.put("password",passwordText);

        HttpUtil.getInstance().post(hashMap, HttpUtil.uri_login, new HttpCallBack() {
            @Override
            public void success(String success) {
//                System.out.println("success>>"+success);

                saveUserNameAndPassword(userNameText,passwordText);
                saveSuccessData(success);

                Platform.runLater(new Runnable() { //主线程中完成 切换线程,否则会报错
                    @Override
                    public void run() {
                        JFXSnackbar snackbar = new JFXSnackbar(root_view);
                        snackbar.fireEvent(new JFXSnackbar.SnackbarEvent(new JFXSnackbarLayout("登录成功")));

                        FXMLLoader loader = new FXMLLoader();
                        loader.setLocation(Main.class.getResource("view/main.fxml"));  //静态读取,无法获取controller
                        try {
                            GridPane rootLayout = loader.load();
                            Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); //设置全屏
                            Scene scene = new Scene(rootLayout, primaryScreenBounds.getMaxX(), primaryScreenBounds.getMaxY());
                            primaryStage.setMaximized(true);
                            primaryStage.setScene(scene); //设置新界面
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void fail(String fail) {
                Platform.runLater(new Runnable() { //主线程中完成
                    @Override
                    public void run() {
                        JFXSnackbar snackbar = new JFXSnackbar(root_view);
                        snackbar.fireEvent(new JFXSnackbar.SnackbarEvent(new JFXSnackbarLayout(fail)));
                    }
                });
            }
        });

    }

保存数据的方法

  /**
     * 保存登录成功的数据,这里将数据保存到Properties文件中,方式如下保存用户名密码类似
     * @param success
     */
    private void saveSuccessData(String success) {
    }

保存用户名密码

 /**
     * 记住密码
     *@param loginName
     * @param passWord
     */
    private void saveUserNameAndPassword(String loginName, String passWord) {
        Properties prop = new Properties();
        try {
            FileOutputStream oFile = new FileOutputStream("user.properties", false);
            prop.setProperty(loginName, passWord);
            prop.store(oFile, null);
            oFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 还原密码
     */
    public void initialize() {
        Properties prop = new Properties();
        try {
            File file = new File("user.properties");
            boolean exists = file.exists();
            if (exists) {
                InputStream in = new BufferedInputStream(new FileInputStream("user.properties"));
                prop.load(in);
                Iterator it = prop.stringPropertyNames().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    userName.setText(key);
                    password.setText(prop.getProperty(key));
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果

javafx 五、网络请求_第2张图片
点击登录后,成功,跳转到新的界面
javafx 五、网络请求_第3张图片

你可能感兴趣的:(javaFx)