I am trying to call remote servlet from GWT, actually the GWT-RPC doesn't seems to work, so I am trying to do it using the RequestBuilder.
Here's the code snippet:
String url = "http://some-remote-host:8888/GWTJSTest/SomeServlet?name=" + textBox.getText();
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
// requestBuilder.setHeader("Origin", "*");
// requestBuilder.setHeader("Access-Control-Allow-Origin", "*");
try
{
requestBuilder.sendRequest(null, new RequestCallback()
{
public void onResponseReceived(Request request, Response response)
{
if (response.getStatusCode() == 200)
{
Window.alert(response.getText());
}else
{
Window.alert(response.getText() + " : " + response.getStatusCode() + response.getStatusText());
}
}
public void onError(Request arg0, Throwable arg1)
{
Window.alert(arg1.toString());
}
});
} catch (RequestException e)
{
Window.alert("CATCH BLOCK: " + e.getMessage());
e.printStackTrace();
}
Actually, IE8 returns the data but after a warning message, but Firefox doesn't! Why is this?
As you see, I am trying to set some request headers but no way.
If you're trying to make a request to your own server and port (the same one that your GWT page is on), replace the first line with:
String url = "/GWTJSTest/SomeServlet?name=" + textBox.getText();
If you're trying to talk to a different server, or a different port on your own server, the Same Origin Policy will keep you from doing that. You'll need to proxy it from your own server.
The remote servlet is the one that needs to set the CORS header that you have:
Access-Control-Allow-Origin: *
Alternatively you can specify just your own domain instead of * if you don't want other domains interacting with the remote servlet.
I've added :
<add-linker name="xs" /> to .gwt.xml
And then replaces GWT-PRC by JsonpRequestBuilder (transforming JSONP between the server and the client)
Related
I'm trying to get data from a php web service (that I've put in my localhost - tested and works fine) in the client side of my GWT application.
I've tried to use the following package com.google.gwt.http.client.* it looks like the code works fine but the response is always 0, it's highly likely to be a corss problem but I still can't figure how to solve it even though I've tried to use requestBuilder.setHeader(..);
here's the code I'm working on:
String url = "http://localhost/geoTrackerTest.php?id=15";
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");
try {
Request request = requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
GWT.log("Error: "+exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
GWT.log("response: "+response.getText());
} else {
GWT.log("response code: "+response.getStatusCode());
}
}
});
} catch (RequestException e) {
GWT.log("Request Exception: "+e.getMessage());
}
I'm still getting 0 as a response.
You will need to set the header in response from server side (not from the GWT client side), then you can make Cross Site Requests from GWT RequestBuilder. Something like this on server side:
Response.setHeader("Access-Control-Allow-Origin","http://localhost");
If you only need to send GET requests, you can use JSONP (http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html) instead to send cross domain requests, without headers setting on server side.
This code is for getting the text from some URL which is having custom authentication as specified below.Tried with even ajax and Jquery as dataType:"jsonp" but it is also showing 401 error.
URL u;
HttpURLConnection con;
InputStream is = null;
DataInputStream dis;
String s;
try {
// u = new URL("http://q.addthis.com/feeds/1.0/trending.json?pubid=atblog");
u = new URL("http://m2mportal.connectm.com/EMS/rest/device");
is = u.openStream();
con=(HttpURLConnection) u.openConnection();
con.connect();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Accept","application/json");
con.setRequestProperty("Authorization","authenticate\":{\"userName\":\"admin01\",\"password\":\"admin01$\",\"appId\":\"123\"}");
con.setRequestProperty("userName","admin01");
con.setRequestProperty("password","admin01$");
con.setRequestProperty("appId","123");
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null)
{
System.out.println(s);
}
}
catch (MalformedURLException mue)
{
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
}
catch (IOException ioe)
{
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
}
catch(IllegalStateException ise)
{
System.out.println("In IllegalState Exception........");
ise.printStackTrace();
}
When tried to authenticate against a url which is having some custom authentication as shown in the code it is returning 401 error
Oops- an IOException happened.
java.io.IOException: Server returned HTTP response code: 401 for URL: some url
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at java.net.URL.openStream(URL.java:1037)
at com.techm.JavaGetUrl.main(JavaGetUrl.java:16)
Java Result: 1
Actually problem here is Authorization property that you passed is not encoded.
You need to pass it to Base64 encoder so that http Authorization mechanism will use it.
Base64 encoding is commonly used when there is a need to encode / decode binary data stored and transferred over network.
Add encoding to your code . change your code to :
you need to use
Base64.encodeToString()
to perform encoding.
Following link will help you more:
http://www.javatips.net/blog/2011/08/how-to-encode-and-decode-in-base64-using-java
I have already tried a lot of approaches to send a xml file as string + pictures with a POST request using GWT on the client side. I can send the strings successfully, but I do not know how to send files (pictures) using the RequestBuilder, I am just able to send the strings.
Do someone know how to send files with a multipart/form-data POST request using GWT Client (RequestBuilder)?
P.S.: As I am not wishing to upload files, I don't need a uploader or something similar. I am developing a mobile app with Phonegap, and making pictures, which should be sent per POST request to a server (a third party service).
Thanks in advance!
Here some code:
public void sendPost() throws RequestException {
String boundary = createBoundary();
String xml = "<note> <to>Müller</to> <from>Jani</from> <heading>Erinnerung</heading> <body>Ich wohne in der Leipzigerstraße</body> </note>";
String requestData = getRequestData(boundary, xml);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "http://localhost:8080/xxx/yyy");
builder.setHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary);
builder.setHeader("Content-Length", Long.toString(requestData.length()));
try {
builder.sendRequest(requestData, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
}
public void onError(Request request, Throwable exception) {
exception.printStackTrace();
}
});
} catch (RequestException e) {
e.printStackTrace();
}
}
private String getRequestData(String boundary, String xml) {
String s = "";
s += "--" + boundary + "\r\n";
s += getRequestParameter("xml", xml + "");
s += "--" + boundary + "--\r\n"; // end
return s;
}
private String getRequestParameter(String key, String value) {
return "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n"
+ value + "\r\n";
}
private String createBoundary() {
return "----GoneVerticalBoundary" + getRandomStr() + getRandomStr();
}
private String getRandomStr() {
return Long.toString(random.nextLong(), 36); //random -> DEFINED IN THE CLASS BODY
}
If you are using gwt + phonegap you should be using gwt-phonegap, right?
What I do in my apps, is to use gwtupload for the desktop version, and phonegap file transfer in the mobile. I use gwtupload servlet in the server side for both cases.
This is my code using gwt-phonegap:
FileUploadOptions options = new FileUploadOptions();
options.setFileKey("file");
options.setFileName("my_file.txt");
options.setMimeType("text/plain");
phonegap.getFile().createFileTransfer().upload(
"file:///my_path/my_file.txt",
"http://my-gwtupload-servlet/servlet.gupld",
options,
new FileUploadCallback() {
#Override
public void onSuccess(FileUploadResult result) {
if (result.getResponseCode() == 200) {
} else {
}
}
#Override
public void onFailure(FileTransferError error) {
Window.alert("Error sending the file, error-code: " + error.getCode());
}
});
I use deferred binding for selecting the appropriate implementation using phonegap.env:
<replace-with class="...UploadFilePhoneGap">
<when-type-is class="....UploadFile" />
<when-property-is name="phonegap.env" value="yes" />
</replace-with>
If you are looking for pure gwt solution then you need to work with FileUpload
If you do not mind using third party open source jar then you can try gwtupload
For locale issues just ensure you are using UTF-8 and GWT locale cookies and locale settings.
For all the people who wants to manage files and pictures on the client side, before sending them to the server, as Manolo has recommended, I suggest lib-gwt-file.
For people working with PhoneGap, I suggest enconding the pictures using Base64, and decoding on the server side (see class Base64Util)
I'm a GWT beginner. I debug my program in GWT development mode. The url is http://127.0.0.1:8888/Replayer.html?gwt.codesvr=127.0.0.1:9997.
I want to get data from existing server which provided data in json format. My code is:
String url = "http://i.abc.com?sid=" + mSessionId + "&action=info";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP
// violation, etc.)
Window.alert("Get fudao info error");
mPrepare = false;
}
#Override
public void onResponseReceived(Request request, Response response) {
GWT.log("statuscode:"+response.getStatusCode());
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
Window.alert(response.getText());
mPrepare = true;
} else {
// Handle the error. Can get the status text from
// response.getStatusText()
Window.alert("Get fudao info wrong");
mPrepare = false;
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
When run the application, the request failed and its status was "canceled". Is it the reason that I cannot request remote server address from localhost for SOP restrictions?
How to fetch data of remote server in GWT development mode?
Normally can't fetch data from another server form GWT client code. But your local server can serve as proxy, e.g. you sending request to your local server, it will send request to remote server, than it will get response from remote server and give it to the GWT client code. This is basically the easiest solution.
I am using RequestBuilder on the front end of GWT to send a HTTP GET request to a Restlet Web Service. However, the request can get into the web service and the web service return a String (in the format of JSON). The problem is no response is returned when I monitor the process through fireBug. Anybody knows why?
Here is the code:
String url = "http://localhost:8080/Books";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception)
{
exception.printStackTrace();
Window.alert("fail - " + exception.getMessage());
}
public void onResponseReceived(Request request, Response response)
{
Window.alert("success - " + response.getText());
}
});
} catch (RequestException e)
{
e.printStackTrace();
}
response.getText() always return empty.
Thanks in advance!
Ike
Do you do your call to a Restlet server on the same host and port that served the webpage that makes the request ?
I am guessing you are running into http://en.wikipedia.org/wiki/Same_origin_policy
Your problem is the Same Origin Policy. The protocol, domain and port in all your requests must be the same as those where your GWT app is being served. If you're serving in Eclipse at port 8888 and your custom server is at port 8080, this won't be trivial.
Try configuring an apache server to proxy e.g. requests to http://localhost/gwt-app.html to http://localhost:8888/gwt-app.html and everything else to your server at http://localhost:8080/*