Have you considered checking the Content-Length header as per the RFC? You could then check if this exceeds some acceptable value -- in your case 2MB -- and reject further processing. You could accomplish this with an initial HTTP HEAD
request and then a GET
if you're happy, or by reading the headers of just the GET
response and proceeding with further streaming if acceptable.
Alternatively (but admittedly ugly), you could use a BufferedReader
passing in a buffer of 2MB and comparing that with the headers.
As for corruption, you're better off using a checksum as stated in other comments. Of course, this requires you knowing the checksum for the resource up-front, and is not something you're likely to get from the HTTP response itself.