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);
}
});
}