下面列出了org.apache.http.util.Args#check ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check that content length less then Integer.MAX_VALUE.
* Try to get content length from entity
* If length less then zero return 4096
*
* @param entity HttpEntity for get capacity.
* @return Capacity.
*/
private int getCapacity(final HttpEntity entity) {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int capacity = (int) entity.getContentLength();
if (capacity < 0) {
capacity = 4096;
}
return capacity;
}
@Override
public void doSendResponse(RestResponse response) {
status = response.status().getStatus();
byte[] bytes = response.content().toBytes();
long length = bytes.length;
Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
if(length < 0) {
length = 4096;
}
InputStream instream = new ByteArrayInputStream(bytes);
InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
CharArrayBuffer buffer = new CharArrayBuffer((int)length);
char[] tmp = new char[1024];
int l;
try {
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
content = buffer.toString();
} catch (IOException e) {
status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
content = "IOException: " + e.getMessage();
} finally {
try {
reader.close();
instream.close();
} catch (IOException e1) {
content = "IOException: " + e1.getMessage();
} finally {
count.countDown();
}
}
}
private static final byte[] toByteArray(final HttpEntity entity,
int maxContent, MutableBoolean trimmed) throws IOException {
if (entity == null)
return new byte[] {};
final InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int reportedLength = (int) entity.getContentLength();
// set default size for buffer: 100 KB
int bufferInitSize = 102400;
if (reportedLength != -1) {
bufferInitSize = reportedLength;
}
// avoid init of too large a buffer when we will trim anyway
if (maxContent != -1 && bufferInitSize > maxContent) {
bufferInitSize = maxContent;
}
final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize);
final byte[] tmp = new byte[4096];
int lengthRead;
while ((lengthRead = instream.read(tmp)) != -1) {
// check whether we need to trim
if (maxContent != -1 && buffer.length() + lengthRead > maxContent) {
buffer.append(tmp, 0, maxContent - buffer.length());
trimmed.setValue(true);
break;
}
buffer.append(tmp, 0, lengthRead);
}
return buffer.toByteArray();
}