我正在使用jersey客户端对API进行REST调用,该API在mulipart中返回Json和PDF文件作为响应的第一部分和第二部分。
final Client client = ClientBuilder.newClient();
final WebTarget target = client.target(endPoint);
final Builder request = target.request().header("Authorization", authKey);
final Response response = request.get();
final String readEntity = response.readEntity(String.class);
这将返回字节代码格式的PDF文件的字符串响应。 我试图将实体读作 MultiPart 类,然后我得到一个异常消息正文阅读器找不到媒体类型= multipart / form-data; boundary = ------ ## ## 和客户端上的 getMediaType()调用返回 multipart / form-data; boundary = ------ #### 。
使用上述客户端解析此多部分响应的正确方法是什么?
答案 0 :(得分:2)
快速Google搜索会为您提供结果。您必须启用MultiPartFeature
并执行response.readEntity(InputStream.class)
从http://www.benchresources.net/jersey-2-x-web-service-for-uploadingdownloading-zip-file-java-client/
获得以下代码 // invoke service after setting necessary parameters
clientConfig = new ClientConfig();
clientConfig.register(MultiPartFeature.class);
client = ClientBuilder.newClient(clientConfig);
client.property("accept", "application/zip");
webTarget = client.target(httpURL);
// invoke service
invocationBuilder = webTarget.request();
// invocationBuilder.header("Authorization", "Basic " + authorization);
response = invocationBuilder.get();
// get response code
responseCode = response.getStatus();
System.out.println("Response code: " + responseCode);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed with HTTP error code : " + responseCode);
}
// get response message
responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
// read response string
inputStream = response.readEntity(InputStream.class);
qualifiedDownloadFilePath = DOWNLOAD_FILE_LOCATION + "MyJerseyZippedFile.zip";
outputStream = new FileOutputStream(qualifiedDownloadFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
答案 1 :(得分:0)
我希望以下代码能为您提供帮助。
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(username,password ))
WebResource webResource = client.resource("URL");
ClientResponse response = webResource.accept("*/*").type(MediaType.APPLICATION_OCTET_STREAM).get(ClientResponse.class);
Assert.assertEquals(response.getStatus(), 200);
MultivaluedMap<String, String> headers = response.getHeaders();
System.out.println("Content-Disposition :" + headers.get("Content-Disposition"));
List<String> filename=headers.get("Content-Disposition");
file_name=filename.get(0);
file_name=file_name.substring(file_name.indexOf("\"")+1,file_name.lastIndexOf("\""));
File file=new File(file_name);
if(!file.exists()) {
file.createNewFile();
}
InputStream inputStream=response.getEntityInputStream();
FileOutputStream fileStream =
new FileOutputStream(file);
IOUtils.copy(inputStream, fileStream);
fileStream.flush();
fileStream.close();
Assert.assertTrue(file.length()>0);
//Deleting the backup file
file.delete();