I have a httpclient which gets a streamed xls file and writes it to a temp file. However, the response can return an error message with a 200 code.
Is there anyway of checking the responseBody streamed back before it's written to the file.
For example, if there is an error, it will return HTML with the word ERROR within it. So I would like to check for that, if it exists, exit the method and return a failure code to the front end.
The front end uses an AJAXRequest called from within an extjs grid.
public void getReport(String login, String date, String type, String id){
String url = "http://...";
HttpClient client = new HttpClient();
KerberizedNetegrityClient auth;
try {
auth = new KerberizedNetegrityClient();
cookie = auth.getCookieToken();
} catch (NetegrityClientException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
GetMethod method = new GetMethod(url);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.setRequestHeader("Cookie", cookie);
try{
int statusCode = client.executeMethod(method);
if(statusCode != HttpStatus.SC_OK){
System.err.println("Method Failed: "+method.getStatusLine());
}
file = "file.xls";
InputStream is = method.getResponseBodyAsStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[8192];
int count = bis.read(bytes);
while(count != -1 && count <= 8192){
System.err.println("-");
fos.write(bytes,0,count);
count = bis.read(bytes);
}
if(count != -1){
fos.write(bytes,0,count);
}
fos.close();
bis.close();
method.releaseConnection();
System.out.println("Done");
}catch (HTTPException e){
System.err.println("Fatal protocol violation: "+ e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: "+ e.getMessage());
e.printStackTrace();
}finally{
method.releaseConnection();
}
streamReport(file);
}
The response should have content-type
header. Just check, if it's text/html
, then it's an error, if it's application/ms-excel
or application/vnd.ms-excel
(not sure, check yours), then it's that you want. Also the excel response usually has content-disposition
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.