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.
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
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With