下面列出了org.apache.http.HttpStatus#SC_MULTIPLE_CHOICES 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
*
* If the linked content is not already downloaded it triggers a download. Then it stores the response
* for later use.<br>
*
* @param downloadIfNeeded indicates if a request should be performed this hasn't been done previously
* @param request the request; if null getWebRequest() is called to create one
* @return {@code null} if no download should be performed and when this wasn't already done; the response
* received when performing a request for the content referenced by this tag otherwise
* @throws IOException if an error occurs while downloading the content
*/
public WebResponse getWebResponse(final boolean downloadIfNeeded, WebRequest request) throws IOException {
if (downloadIfNeeded && cachedWebResponse_ == null) {
final WebClient webclient = getPage().getWebClient();
if (null == request) {
request = getWebRequest();
}
try {
cachedWebResponse_ = webclient.loadWebResponse(request);
final int statusCode = cachedWebResponse_.getStatusCode();
final boolean successful = statusCode >= HttpStatus.SC_OK
&& statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
if (successful) {
executeEvent(Event.TYPE_LOAD);
}
else {
executeEvent(Event.TYPE_ERROR);
}
}
catch (final IOException e) {
executeEvent(Event.TYPE_ERROR);
throw e;
}
}
return cachedWebResponse_;
}
public static String executeHttpRequest(CloseableHttpClient httpClient, HttpRequestBase request,
String encoding) throws IOException {
try {
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
if (status >= HttpStatus.SC_OK
&& status < HttpStatus.SC_MULTIPLE_CHOICES) {
return IOUtils.toString(response.getEntity().getContent(),
encoding);
} else {
logger.error("the response status code {} is illegal", status);
throw new GeneralRuntimeException(
HttpClientConstants.HTTP_RESPONSE_STATUS_ERROR.toString());
}
} finally {
httpClient.close();
}
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
*
* <p>Logs the response's content if its status code indicates a request failure and
* {@link WebClientOptions#isPrintContentOnFailingStatusCode()} returns {@code true}.
*
* @param webResponse the response whose content may be logged
*/
public void printContentIfNecessary(final WebResponse webResponse) {
if (getOptions().isPrintContentOnFailingStatusCode()) {
final int statusCode = webResponse.getStatusCode();
final boolean successful = statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
if (!successful && LOG.isInfoEnabled()) {
final String contentType = webResponse.getContentType();
LOG.info("statusCode=[" + statusCode + "] contentType=[" + contentType + "]");
LOG.info(webResponse.getContentAsString());
}
}
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
*
* <p>Throws a {@link FailingHttpStatusCodeException} if the request's status code indicates a request
* failure and {@link WebClientOptions#isThrowExceptionOnFailingStatusCode()} returns {@code true}.
*
* @param webResponse the response which may trigger a {@link FailingHttpStatusCodeException}
*/
public void throwFailingHttpStatusCodeExceptionIfNecessary(final WebResponse webResponse) {
final int statusCode = webResponse.getStatusCode();
final boolean successful = (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES)
|| statusCode == HttpStatus.SC_USE_PROXY
|| statusCode == HttpStatus.SC_NOT_MODIFIED;
if (getOptions().isThrowExceptionOnFailingStatusCode() && !successful) {
throw new FailingHttpStatusCodeException(webResponse);
}
}
/**
* isStatusOK - Checks if we have a status in the 2xx range
*
* @param statusLine - the status line containing the code
* @return whether the status x is in the range [200, 300)
*/
private static boolean isStatusOK(StatusLine statusLine)
{
//If the status is 200 (OK) or greater but less than 300 (Multiple Choices) we're good
return statusLine.getStatusCode() >= HttpStatus.SC_OK
&& statusLine.getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES;
}
/**
* Reponseボディを受ける場合のHTTPリクエストを行う.
* @param httpReq HTTPリクエスト
* @return DCレスポンスオブジェクト
* @throws DaoException DAO例外
*/
protected DcResponse request(final HttpUriRequest httpReq) throws DaoException {
try {
HttpResponse objResponse = httpClient.execute(httpReq);
DcResponse dcRes = new DcResponse(objResponse);
int statusCode = objResponse.getStatusLine().getStatusCode();
if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
throw DaoException.create("{\"io exception\" : " + dcRes.bodyAsString() + "}", statusCode);
}
return dcRes;
} catch (IOException ioe) {
throw DaoException.create("{\"io exception\" : " + ioe.getMessage() + "}", 0);
}
}
@Override
protected void validateResponse(HttpInvokerClientConfiguration config, HttpResponse response) throws HttpException {
int statusCode = response.getStatusLine().getStatusCode();
// HTTP status codes in the 200-299 range indicate success
if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES /* 300 */) {
throw new HttpException(statusCode, "Did not receive successful HTTP response: status code = " + statusCode +
", status message = [" + response.getStatusLine().getReasonPhrase() + "]");
}
}
private Boolean isSuccess(int statusCode) {
return statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
}
/**
* <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
*
* <p>Executes this element's <tt>onload</tt> or <tt>onerror</tt> handler. This method downloads the image
* if either of these handlers are present (prior to invoking the resulting handler), because applications
* sometimes use images to send information to the server and use these handlers to get notified when the
* information has been received by the server.</p>
*
* <p>See <a href="http://www.nabble.com/How-should-we-handle-image.onload--tt9850876.html">here</a> and
* <a href="http://www.nabble.com/Image-Onload-Support-td18895781.html">here</a> for the discussion which
* lead up to this method.</p>
*
* <p>This method may be called multiple times, but will only attempt to execute the <tt>onload</tt> or
* <tt>onerror</tt> handler the first time it is invoked.</p>
*/
public void doOnLoad() {
if (onloadProcessed_) {
return;
}
final HtmlPage htmlPage = getHtmlPageOrNull();
if (htmlPage == null) {
return; // nothing to do if embedded in XML code
}
final WebClient client = htmlPage.getWebClient();
final boolean hasEventHandler = hasEventHandlers("onload") || hasEventHandlers("onerror");
if (((hasEventHandler && client.isJavaScriptEnabled())
|| client.getOptions().isDownloadImages()) && hasAttribute(SRC_ATTRIBUTE)) {
boolean loadSuccessful = false;
final boolean tryDownload;
if (hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY)) {
tryDownload = !StringUtils.isBlank(getSrcAttribute());
}
else {
tryDownload = !getSrcAttribute().isEmpty();
}
if (tryDownload) {
// We need to download the image and then call the resulting handler.
try {
downloadImageIfNeeded();
final int i = imageWebResponse_.getStatusCode();
// if the download was a success
if ((i >= HttpStatus.SC_OK && i < HttpStatus.SC_MULTIPLE_CHOICES)
|| i == HttpStatus.SC_USE_PROXY) {
loadSuccessful = true; // Trigger the onload handler
}
}
catch (final IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("IOException while downloading image for '" + this + "' : " + e.getMessage());
}
}
}
if (!client.isJavaScriptEnabled()) {
onloadProcessed_ = true;
return;
}
if (!hasEventHandler) {
return;
}
onloadProcessed_ = true;
final Event event = new Event(this, loadSuccessful ? Event.TYPE_LOAD : Event.TYPE_ERROR);
if (LOG.isDebugEnabled()) {
LOG.debug("Firing the " + event.getType() + " event for '" + this + "'.");
}
if (READY_STATE_LOADING.equals(htmlPage.getReadyState())) {
final PostponedAction action = new PostponedAction(getPage()) {
@Override
public void execute() throws Exception {
HtmlImage.this.fireEvent(event);
}
};
htmlPage.addAfterLoadAction(action);
}
else {
fireEvent(event);
}
}
}
private int computeStatus(int status) {
switch (status) {
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PAYMENT_REQUIRED:
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_NOT_ACCEPTABLE:
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_CONFLICT:
case HttpStatus.SC_GONE:
case HttpStatus.SC_LENGTH_REQUIRED:
case HttpStatus.SC_PRECONDITION_FAILED:
case HttpStatus.SC_REQUEST_TOO_LONG:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
case HttpStatus.SC_EXPECTATION_FAILED:
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_METHOD_FAILURE:
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_LOCKED:
case HttpStatus.SC_FAILED_DEPENDENCY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_NOT_IMPLEMENTED:
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case HttpStatus.SC_GATEWAY_TIMEOUT:
case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
return 0;
case HttpStatus.SC_CONTINUE:
case HttpStatus.SC_SWITCHING_PROTOCOLS:
case HttpStatus.SC_PROCESSING:
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
case HttpStatus.SC_NO_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_MULTIPLE_CHOICES:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_NOT_MODIFIED:
case HttpStatus.SC_USE_PROXY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return 1;
default :
return 1;
}
}
public static boolean isHttpStatusCodeSuccess(final int pHttpStatusCode) {
return pHttpStatusCode >= HttpStatus.SC_OK && pHttpStatusCode < HttpStatus.SC_MULTIPLE_CHOICES;
}
public FileResponse(String u, Metadata md, FileProtocol fileProtocol)
throws IOException {
metadata = new Metadata();
content = new byte[0];
statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
URL url = new URL(u);
if (!url.getPath().equals(url.getFile())) {
LOG.warn("url.getPath() != url.getFile(): {}.", url);
}
String path = "".equals(url.getPath()) ? "/" : url.getPath();
File file = new File(
URLDecoder.decode(path, fileProtocol.getEncoding()));
if (!file.exists()) {
statusCode = HttpStatus.SC_NOT_FOUND;
return;
}
if (!file.canRead()) {
statusCode = HttpStatus.SC_UNAUTHORIZED;
return;
}
if (!file.equals(file.getCanonicalFile())) {
metadata.setValue(HttpHeaders.LOCATION, file.getCanonicalFile()
.toURI().toURL().toString());
statusCode = HttpStatus.SC_MULTIPLE_CHOICES;
return;
}
if (file.isDirectory()) {
getDirAsHttpResponse(file);
} else if (file.isFile()) {
getFileAsHttpResponse(file);
} else {
statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
return;
}
}
/**
* Determines if an HttpResponse can be cached.
*
* @param httpMethod
* What type of request was this, a GET, PUT, other?
* @param response
* The origin response
* @return <code>true</code> if response is cacheable
*/
public boolean isResponseCacheable(String httpMethod, HttpResponse response) {
boolean cacheable = false;
if (!HeaderConstants.GET_METHOD.equals(httpMethod)) {
log.debug("Response was not cacheable.");
return false;
}
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
case HttpStatus.SC_MULTIPLE_CHOICES:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_GONE:
// these response codes MAY be cached
cacheable = true;
log.debug("Response was cacheable");
break;
case HttpStatus.SC_PARTIAL_CONTENT:
// we don't implement Range requests and hence are not
// allowed to cache partial content
log.debug("Response was not cacheable (Partial Content)");
return cacheable;
default:
// If the status code is not one of the recognized
// available codes in HttpStatus Don't Cache
log.debug("Response was not cacheable (Unknown Status code)");
return cacheable;
}
Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
if (contentLength != null) {
int contentLengthValue = Integer.parseInt(contentLength.getValue());
if (contentLengthValue > this.maxObjectSizeBytes)
return false;
}
Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE);
if (ageHeaders.length > 1)
return false;
Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES);
if (expiresHeaders.length > 1)
return false;
Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER);
if (dateHeaders.length != 1)
return false;
try {
DateUtils.parseDate(dateHeaders[0].getValue());
} catch (DateParseException dpe) {
return false;
}
for (Header varyHdr : response.getHeaders(HeaderConstants.VARY)) {
for (HeaderElement elem : varyHdr.getElements()) {
if ("*".equals(elem.getName())) {
return false;
}
}
}
if (isExplicitlyNonCacheable(response))
return false;
return (cacheable || isExplicitlyCacheable(response));
}