再次感谢 Jewelsea - 他很好地回答了许多 JavaFX 问题。我想分享这个解决方案,它在我的测试中非常适合我的应用程序。我正在发出 Jersey-Client REST 请求,并将其放在我的 JavaFX 应用程序中(没有创建扩展 javafx.concurrent.Service 的单独类)。
所以我在下面所做的是提供对我来说很好的解决方案,考虑到上面提供的链接jewelsea。成功 POST 到提供的 url 后,此 Service 类将返回一个 ClientResponse 对象。我试图在下面的评论中提供更多关于此的说明。
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
/**
* This Service class will make REST calls to a given URL,
* with a JSON encoded request string.
*
* OnSucceeded will return a ClientResponse object - will be
* null if an exception occurred - if no exception is the
* ClientResponse result of the Jersey-Client call.
*/
public class JerseyClientPostService extends Service<ClientResponse> {
private StringProperty url = new SimpleStringProperty();
private StringProperty json = new SimpleStringProperty();
public JerseyClientPostService() {
super();
}
public JerseyClientPostService(String url, String json) {
super();
this.url.set(url);
this.json.set(json);
}
public final String getUrl() {
return this.url.get();
}
public final String getJson() {
return this.json.get();
}
public final void setJson(String json) {
this.json.set(json);
}
public final void setUrl(String url) {
this.url.set(url);
}
@Override protected Task<ClientResponse> createTask() {
final String _url = getUrl();
final String _json = getJson();
return new Task<ClientResponse>() {
@Override protected ClientResponse call() {
Client client = Client.create();
WebResource webResource = client.resource(_url);
ClientResponse response;
try {
response = webResource.type("application/json").post(ClientResponse.class, _json);
}
catch (ClientHandlerException che) {
System.err.println("ClientHandlerException connecting to Server: "+che.getMessage());
return null;
}
catch (Exception ex) {
System.err.println("Exception getting response Json: "+ex.getMessage());
return null;
}
return response;
}
};
}
}