繁体   English   中英

Play Framework:如何使用WS客户端读取png图像?

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

嗨,我想从网络服务中读取PNG,然后使用PNG回复客户端。 (想想像图像代理)。 我正在使用Java和Play Framework 2.0与WS类。

目前我有:

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?

}

任何帮助深表感谢。

在Play 2.0.4中,你不能用Java做到这一点。 首先,API中没有二进制文件的方法: http//www.playframework.org/documentation/api/2.0.4/java/play/libs/WS.Response.html 我尝试了WS.Response.getBody()方法,但字节不正确。

但是Scala API支持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")
      }
    }
  }

}

从Play 2.1开始,Java中支持二进制文件: https//github.com/playframework/Play20/blob/master/framework/src/play-java/src/main/java/play/libs/WS.java# L565

谢谢,看起来我必须耐心:)。 我找到了一个解决方法(直接使用ning)。

//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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM