假设有一个第三方RESTful Web服务公开了一个GET端点:
http://someservice.com/api/askAnyQuestion
我想点击该服务,将我的问题放在查询字符串上:
http://someservice.com/api/askAnyQuestion&q=Does%20my%20dog%20know%20about%20math%3F
如何从客户端GWT应用程序中获取此服务?我一直在阅读RequestFactory
教程,但RF似乎仅用于提供数据访问层( DAL)和CRUDding实体,我不完全确定它是否适合这个用例。
如果有人可以提供代码示例,而不仅仅是我已经阅读的GWT教程的链接,或者我也可能阅读过的一些Googler的博客,那么额外的超级奖励积分; - )。
答案 0 :(得分:1)
您可以使用RequestBuilder。成功地将它用于REST。
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onError(Request request, Throwable exception) {
// process error
}
@Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// process success
} else {
// process other HTTP response codes
}
}
});
} catch (RequestException e) {
// process exception
}
请同时查看this question以获取有关跨网站请求的相关信息。
答案 1 :(得分:0)
前几天我遇到了同样的问题,并试图用requestBuilder实现它。您将收到跨域脚本问题。
我通过对我的服务器的RPC请求以及从那里的服务器端HTTP请求到跨域URL来处理这个问题。
https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite
public static void SendRequest(String method, String notifications) {
String url = SERVICE_BASE_URL + method;
JSONObject requestObject = new JSONObject();
JSONArray notificationsArray =null;
JSONObject mainRequest = new JSONObject();
try {
notificationsArray = new JSONArray(notifications);
requestObject.put("notifications", notificationsArray);
mainRequest.put("request", requestObject);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try
{
URL server = new URL(url);
connection = (HttpURLConnection) server.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(mainRequest.toString());
writer.flush();
writer.close();
parseResponse(connection);
}
catch (Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
}