Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework: How can I read a png image using the WS client?

Hi I'd like to read a PNG from a web service and then respond back to the client with the PNG. (think something like an image proxy). I am using Java and the Play Framework 2.0 with the WS class.

Currently I have:

public static Result getimage(){

  WSRequestHolder requestHolder = WS.url("http://someimageserver/myimage.png");
  Promise<WS.Response> getImageResult = requestHolder.get();
  //How do I create an play.mvc.Result from this so I can sent it back to the callee?

}

Any help is much appreciated.

like image 935
user1887568 Avatar asked Dec 08 '12 10:12

user1887568


2 Answers

In Play 2.0.4 you can't do that in Java. First there is no method for binaries in the API: http://www.playframework.org/documentation/api/2.0.4/java/play/libs/WS.Response.html . I tried the method WS.Response.getBody(), but the bytes weren't correct.

But the Scala API supports binary files in Play 2.0.4:

package controllers

import play.api._
import libs.ws.WS
import play.api.mvc._

object Application extends Controller {

  def getImage = Action {
    Async {
      WS.url("http://someimageserver/myimage.png").get().map { r =>
        Ok(r.getAHCResponse.getResponseBodyAsBytes).as("image/png")
      }
    }
  }

}

From Play 2.1 on there is support for binaries in Java: https://github.com/playframework/Play20/blob/master/framework/src/play-java/src/main/java/play/libs/WS.java#L565

like image 102
Schleichardt Avatar answered Oct 24 '22 10:10

Schleichardt


Thanks, looks like I'll have to be patient :) . I found a workaround though (using ning directly).

//imports
import java.util.concurrent.Future;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Response;

//request
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
BoundRequestBuilder prepareGet = asyncHttpClient.prepareGet(url);
Future<Response> fResponse = prepareGet.execute();
Response r = fResponse.get();
InputStream responseBodyAsStream = r.getResponseBodyAsStream();

return ok(responseBodyAsStream).as('image/png');
like image 5
user1887568 Avatar answered Oct 24 '22 09:10

user1887568