【发布时间】:2012-12-31 16:47:35
【问题描述】:
我正在使用 Jersey(版本 1.9.1)为 png 图像实现 RESTful Web 服务。我在客户端使用 Apache HttpClient(版本 4x)。客户端的代码调用 HttpGet 来下载图像。成功下载后,它将 InputStream 从 HttpEntity 保存到磁盘。现在问题是生成的文件和服务器上的文件不同。客户端代码生成的输出图像文件不可渲染。
@GET
@Path("/public/profile/{userId}")
@Produces({ "image/png" })
public Response getImage(@PathParam(value = "userId") String userId) {
Response res = null;
// ImageManagement.gerProfilePicture(userId) returns me profile picture
// of the provided userId in PathParam
File imageFile = ImageManagement.getProfilePicture(userId);
if (imageFile == null) {
res = Response.status(Status.NOT_FOUND).build();
} else {
res = Response
.ok(imageFile, "image/png")
.header("Content-Disposition",
"attachment; filename=Img" + userId + ".png")
.build();
}
return res;
}
下面我的客户端代码调用了上面的资源方法
private File downloadProfilePicture(String userId) throws IOException{
// URIHelper is a utility class, this give me uri for image resource
URI imageUri = URIHelper.buildURIForProfile(userId);
HttpGet httpGet = new HttpGet(imageUri);
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
File imageFile = null;
if (statusCode == HttpURLConnection.HTTP_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
Header[] headers = httpResponse.getHeaders("Content-Disposition");
imageFile = new File(OUTPUT_DIR, headers[0].getElements()[0]
.getParameterByName("filename").getValue());
FileOutputStream foutStream = new FileOutputStream(imageFile);
httpEntity.writeTo(foutStream);
foutStream.close();
}
return imageFile;
}
现在的问题是服务器上存在文件和下载的文件不同。
以下是服务器上存在的文件转储。
下面是下载文件的转储。
你可以看到,一些字节被改变了。 Jersey 服务器 api 是否从文件中修改流中的数据?出了什么问题?
更新:
如果我从浏览器点击相同的 url,它会下载文件但下载的文件不可见。所以这个问题似乎与服务器有关。
【问题讨论】:
-
服务器提供的文件是正确的,例如,您可以在浏览器中显示它吗?
-
是的。它是png格式的。
-
马塞尔问的是,如果你用浏览器请求相同的 URL,你能看到图像吗?如果可以,问题不在于服务器。顺便说一句,在客户端上,您不需要所有代码。只需阅读一个网址
-
两个文件大小相同。我注意到一些字节正在改变。这对我来说似乎是一些编码问题。但不知道发生了什么。
-
Marcel,对不起,我误解了你的问题。如果我从浏览器点击 url,浏览器会下载文件。但是下载的文件是不可见的。所以我相信,问题出在服务器上。
标签: java image jersey apache-httpclient-4.x content-encoding