4

I'm working on a GWT App that makes a REST call for binary data. I'm trying to use GWT's RequestBuilder. The problem is that the response only offers a getText() method.

Here's the simplest example that reproduces the problem:

private static void sendRequest()
{
    String url = URL.encode("/object/object_id");

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);
    try
    {
        requestBuilder.sendRequest("", new RequestCallback()
        {
            @Override
            public void onResponseReceived(Request request, Response response)
            {
                String data = response.getText(); ///< Need this to be a byte[] array (e.g. getData())
            }

            @Override
            public void onError(Request request, Throwable exception)
            {
            }
        });
    }
    catch (RequestException RequestException)
    {
    }
}

The problem is that GWT is encoding the response data as a String in (what I think) is the default platform's encoding. Is there any way to get the data before GWT converts it to a String?

Naijaba
  • 1,019
  • 1
  • 13
  • 24

2 Answers2

3

HTTP can transfer text and binary, but Javascript can only get text via XHR. If you want to send binary data through it then Base64 encode it. GWT can handle Base64.

Update: in recent browsers (end of 2013), the binary array handling can be achieved via TypedArray. See browser support for it.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • I suspected as much. We'll have to modify our API to base 64 encode the data prior to return it. – Naijaba May 18 '11 at 23:54
  • 1
    This is a wrong answer. HTTP can transfer binary data. A common example are images. – maasg Jul 01 '11 at 16:40
  • Yes, I should make it clearer: HTTP can download and upload binary, buy binary is not available to Javascript and hence GWT. – Peter Knego Jan 03 '12 at 18:47
  • Binary is available to JS and GWT thru modern browsers. See TypedArrays and lib-gwt-file from org.vectomatic – Federico Pugnali Dec 30 '13 at 16:21
  • Yes, TypedArrays are a relatively recent addition. They were not supported in mainstream browsers when I wrote the answer. Updating.. – Peter Knego Dec 31 '13 at 10:43
1

You can get binary image in GWT using JSNI. Mind that it doesn't work with IE. This is an example how:

native String getBinaryResource(String url) /*-{
    // ...implemented with JavaScript                 
    var req = new XMLHttpRequest();
    req.open("GET", url, false);  // The last parameter determines whether the request is asynchronous -> this case is sync.
    req.overrideMimeType('text/plain; charset=x-user-defined');
    req.send(null);
    if (req.status == 200) {                    
        return req.responseText;
    } else return null
}-*/;

I just finished researching a similar question where I put additional information: Generating an inline-image with java gwt

Community
  • 1
  • 1
maasg
  • 37,100
  • 11
  • 88
  • 115