JavaFX-OKhttp简易封装

0.前言

JavaFX作为JAVA客户端GUI框架,在使用JavaFX作为前端开发的时候,如果使用了前后端分离的方式开发,脱离了JDBC,那网络请求必不可少,下面选用了比较火热的OKHTTP,JAVA还有很多其他网络请求框架,但是感觉OKHTTP封装起来比较灵活。

1.Gradle导包

因为工程用的Gradle管理工具,需要jar包的可以自己到maven官网下载。

compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.10.0'
compile group: 'com.squareup.okio', name: 'okio', version: '1.14.0'
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.4'

2.建立接口回调类HttpBack

接口回调类用于自定义回调,在建立HttpService 时会用到

package bccsclient.api;
import okhttp3.Call;
public interface HttpBack {
     void onsucess(Call call,String response);
     void onfail(Call call, String e);
}

3.封装类HttpService

OKHTTP设置十分灵活大家可以根据自己需求,修改封装类HttpService

package bccsclient.api;
import bccsclient.util.DialogUtil;
import bccsclient.util.JsonUtil;
import com.google.gson.Gson;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.prefs.Preferences;

/**
 * @Author bb
 * @Create 2018/5/18
 * @Description 网络请求封装类
 */
public class HttpService {
private static final MediaType JSON
        = MediaType.parse("application/json; charset=utf-8");
private static String authorizationHead = "";
private volatile static HttpService INSTANCE;
private volatile static Gson gson;
private volatile static OkHttpClient mOkHttpClient;
private static String baseurl;

private HttpService() {
    mOkHttpClient = new OkHttpClient();

    Preferences preferences = Preferences.userRoot().node(Constant.Preferences_Node);
    baseurl = preferences.get("baseurl", "");
    authorizationHead = preferences.get("authorizationHead", "");

}


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


/**
 * 异步get请求
 *
 * @param uri
 * @param map
 * @param callback
 */
public static void httpGet(String uri, Map<String, String> map, HttpBack callback) {

    if (map.size() != 0) {
        uri = uri + "?";
        for (String in : map.keySet()) {
            String str = map.get(in);
            uri = uri + in + "=" + str + "&";
        }
        uri = uri.substring(0, uri.length() - 1);
    }

    Request request = new Request.Builder()
            .addHeader("authorization", authorizationHead)
            .url(baseurl + uri)
            .get().build();
    Call call = mOkHttpClient.newCall(request);
    callListener(call, callback);
}

/**
 * 异步Post键值对请求
 *
 * @param uri
 * @param map
 * @param callback
 */
public static void httpPostMap(String uri, Map<String, String> map, HttpBack 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("authorization", authorizationHead)
            .url(baseurl + uri)
            .post(body).build();
    Call call = mOkHttpClient.newCall(request);
    callListener(call, callback);
}

/**
 * 异步Post Bean请求
 *
 * @param uri
 * @param Bean
 * @param callback
 * @param <T>
 */
public static <T> void httpPostBean(String uri, T Bean, HttpBack callback) {
    RequestBody body = RequestBody.create(JSON, JsonUtil.bean2Json(Bean));
    Request request = new Request.Builder()
            .addHeader("authorization", authorizationHead)
            .url(baseurl + uri)
            .post(body).build();
    Call call = mOkHttpClient.newCall(request);
    callListener(call, callback);


}


public static void callListener(Call call, HttpBack httpBack) {

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Platform.runLater(() -> {
                httpBack.onfail(call, e);
                DialogUtil.createExceptionDialog("警告", "网络请求异常", e);
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    Object onsucess = httpBack.onsucess(call, response.body().string());
                    Platform.runLater(() -> {
                        httpBack.onsucessView(onsucess);
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Platform.runLater(() -> {
                    httpBack.onfail(call, new Exception(response.message()));
                    DialogUtil.createAlert(Alert.AlertType.WARNING, "网络请求失败" + response.code());
                });
            }
        }
    });
}

}

4.使用HttpService

//http示例1--post
  private void httppost() {

    HttpService.getInstance().httpPostBean("auth", new AuthBean("dengxin", "1"), new HttpBack() {
        @Override
        public Object onsucess(Call call, String response) {
            System.out.println(response);
            return response;
        }

        @Override
        public void onsucessView(Object object) {
            TextArea.setText("请求成功:" + (String) object);
        }

        @Override
        public void onfail(Call call, Exception e) {
            System.out.println("失败");
            TextArea.setText("请求失败:" + e);
        }
    });
}

//http示例2--get请求-带参数
   private void httpget3() {
    Map<String, String> map = new HashMap();
    map.put("projid", "P0001");
    HttpService.getInstance().httpGet("main/tops", map, new HttpBack() {
        @Override
        public Object onsucess(Call call, String response) {
            System.out.println(response);
            JsonUtil.json2JSONArray(response);
            return JsonUtil.json2JSONArray(response);
        }

        @Override
        public void onsucessView(Object object) {
            TextArea.setText("请求成功:" + object);

        }

        @Override
        public void onfail(Call call, Exception e) {
            System.out.println("失败");
            TextArea.setText("请求失败:" + e);
        }
    });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,540评论 25 709
  • 今天下午有一场特别的见面。 源于自己认识的一位老乡,我内心带着互相拓展的想法,权当见一面认识一下。当然在认...
    尹莎阅读 248评论 0 1
  • 灯红酒绿的城市里,喧哗热闹的街市上,一路上人来人往,回家的、工作的、玩乐的……各式各样的人,都在为了什么而行走着。...
    朗月笑长空阅读 526评论 0 0
  • 很多时候的所谓坚强和独立,并不是个性使然,而是别无选择。 回想来时的路,那么多次的低沉、无助,甚至穷迫,但都一声不...
    不吃深海鱼的喵阅读 307评论 0 0
  • 今天赶在中午去理了发。 之所以要中午去理发,因为马上就要过年,一旦腊月二十不理发,此后每天都会涨价,直到正月初一。...
    乌卓阅读 508评论 1 6