I would like to determine the type of a file (generally UTF-8) by reading the first part of the file and analysing the content. (The type is specific to my community but not under my control and not covered by MIME/MediaType which is normally TEXT_PLAIN). I am using the 'org.restlet' library on the client to analyse the header with
Request request = new Request(Method.HEAD, url);
so I know the content-length and can (if necessary and possible) estimate how many bytes I should download for the analysis
CLARIFICATION: I cannot use the MediaType. From answer 1 seems like I have to GET the content. A revised question would therefore be:
"Can I GET part of a file using Restlet?"
ANSWER: The following code does what I want. I have credited @BalusC for showing the way. Please comment if I have missed anything:
public String readFirstChunk(String urlString, int byteCount) {
String text = null;
if (urlString != null) {
org.restlet.Client restletClient = new org.restlet.Client(Protocol.HTTP);
Request request = new Request(Method.GET, urlString);
List<Range> ranges = Collections.singletonList(new Range(0, byteCount));
request.setRanges(ranges);
Response response = restletClient.handle(request);
if (Status.SUCCESS_OK.equals(response.getStatus())) {
text = processSuccessfulChunkRequest(response);
} else if (Status.SUCCESS_PARTIAL_CONTENT .equals(response.getStatus())) {
text = processSuccessfulChunkRequest(response);
} else {
System.err.println("FAILED "+response.getStatus());
}
}
return text;
}
private String processSuccessfulChunkRequest(Response response) {
String text = null;
try {
text = response.getEntity().getText();
} catch (IOException e) {
throw new RuntimeException("Cannot download chunk", e);
}
return text;
}