下面列出了org.apache.http.HttpStatus#SC_FORBIDDEN 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean disabledSkill403(CloseableHttpResponse response) throws IOException {
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_FORBIDDEN) {
return false;
}
HttpEntity entity = null;
try {
entity = response.getEntity();
Map<String, Object> body = JSON.fromJson(EntityUtils.toString(entity, StandardCharsets.UTF_8), ERR_TYPE);
boolean disabled = StringUtils.equals("skill_not_enabled", (String) body.get("error"));
if(disabled) {
logger.warn("disabled skill due to 403 error with body {}", body);
}
return disabled;
} finally {
consumeQuietly(entity);
}
}
@Override
public ActionResult execute() {
String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID);
if (!studentId.equals(userInfo.id) && !isMasqueradeMode()) {
return new JsonResult("You are not authorized to update this student's profile.",
HttpStatus.SC_FORBIDDEN);
}
StudentProfileUpdateRequest updateRequest = getAndValidateRequestBody(StudentProfileUpdateRequest.class);
try {
StudentProfileAttributes studentProfile = sanitizeProfile(extractProfileData(studentId, updateRequest));
logic.updateOrCreateStudentProfile(
StudentProfileAttributes.updateOptionsBuilder(studentId)
.withShortName(studentProfile.shortName)
.withEmail(studentProfile.email)
.withGender(studentProfile.gender)
.withNationality(studentProfile.nationality)
.withInstitute(studentProfile.institute)
.withMoreInfo(studentProfile.moreInfo)
.build());
return new JsonResult(Const.StatusMessages.STUDENT_PROFILE_EDITED, HttpStatus.SC_ACCEPTED);
} catch (InvalidParametersException ipe) {
return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST);
}
}
private void throwExceptionOnBadResponse( Response response ) throws FileSystemException {
final int status = response.getStatus();
switch ( status ) {
case HttpStatus.SC_OK:
logger.debug( "OK" );
// response OK => do not throw exception and continue execution
break;
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_MOVED_TEMPORARILY:
logger.debug( "FORBIDDEN" );
throw new FileSystemException( INVALID_USERNAME_OR_PASSWORD );
default:
logger.debug( "ERROR " + status );
throw new FileSystemException( BAD_RESPONSE, status );
}
}
private BuildInfo handleBuildInfoResponse(String appName, ObjectMapper mapper, CloseableHttpResponse response) throws IOException, HerokuDeployApiException {
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_NOT_FOUND:
throw new AppNotFoundException(String.format("App %s could not be found!", appName));
case HttpStatus.SC_FORBIDDEN:
throw new InsufficientAppPermissionsException(String.format("Could not access app %s: insufficient permissions", appName));
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
HttpEntity responseEntity = response.getEntity();
String responseStringBody = Util.readLinesFromInputStream(responseEntity.getContent()).collect(Collectors.joining());
return mapper.readValue(responseStringBody, BuildInfo.class);
default:
throw new HerokuDeployApiException(String.format("Unexpected status code: %d!", response.getStatusLine().getStatusCode()));
}
}
@Test
public void testInvalidCredentials_JSONRPC() throws Exception {
HttpCallable c = new HttpCallable("json-rpc mixed", RPC_ENDPOINT, MIXED_JSONRPC, HttpStatus.SC_FORBIDDEN);
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Token-Username", "INVALID");
String result = makeRequest(c, null, 0, "RPC", headers, null);
// check result is OK
assertTrue("Error returned: "+result, result.contains("error"));
assertTrue("Error returned: "+result, result.contains("-32099"));
assertTrue("Error returned: "+result, result.contains("DSC-0015"));
}
protected String parseClientLoginResponse(HttpResponse response) throws
AuthClientException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK && status != HttpStatus.SC_FORBIDDEN) {
throw new AuthClientException("Unexpected ClientLogin HTTP status " + status);
}
String body = EntityUtils.toString(response.getEntity());
Map<String, String> responseMap = parseClientLoginBody(body);
if (status == HttpStatus.SC_OK) {
String authToken = responseMap.get("Auth");
if (authToken == null) {
throw new AuthClientException("Auth token missing from ClientLogin response");
}
return authToken;
} else {
String message = "ClientLogin forbidden";
// Base error code (eg. BadAuthentication)
String error = responseMap.get("Error");
if (error != null) {
message += ": " + error;
}
// Additional error code, not usually present (eg. InvalidSecondFactor)
String info = responseMap.get("Info");
if (info != null) {
message += " (" + info + ")";
}
throw new AuthClientException(message);
}
}
@Override
public BackgroundException map(final FailedRequestException e) {
final StringBuilder buffer = new StringBuilder();
if(null != e.getError()) {
this.append(buffer, e.getError().getMessage());
}
switch(e.getStatusCode()) {
case HttpStatus.SC_FORBIDDEN:
if(null != e.getError()) {
if(StringUtils.isNotBlank(e.getError().getCode())) {
switch(e.getError().getCode()) {
case "SignatureDoesNotMatch":
return new LoginFailureException(buffer.toString(), e);
case "InvalidAccessKeyId":
return new LoginFailureException(buffer.toString(), e);
case "InvalidClientTokenId":
return new LoginFailureException(buffer.toString(), e);
case "InvalidSecurity":
return new LoginFailureException(buffer.toString(), e);
case "MissingClientTokenId":
return new LoginFailureException(buffer.toString(), e);
case "MissingAuthenticationToken":
return new LoginFailureException(buffer.toString(), e);
}
}
}
}
if(e.getCause() instanceof IOException) {
return new DefaultIOExceptionMappingService().map((IOException) e.getCause());
}
return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(e.getStatusCode(), buffer.toString()));
}
private static String handleResponse(HttpResponse response, String methodName, boolean retry, int executionCount,
int retryCount, String uri) throws OnPremiseGatewayException {
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
return handleSuccessCase(response);
case HttpStatus.SC_CREATED:
return handleSuccessCase(response);
case HttpStatus.SC_ACCEPTED:
return handleSuccessCase(response);
case HttpStatus.SC_NOT_FOUND:
throw new OnPremiseGatewayException(NOT_FOUND_ERROR_MSG);
case HttpStatus.SC_UNAUTHORIZED:
throw new OnPremiseGatewayException(AUTH_ERROR_MSG);
case HttpStatus.SC_FORBIDDEN:
throw new OnPremiseGatewayException(AUTH_FORBIDDEN_ERROR_MSG);
default:
if (retry) {
handleDefaultCaseWithRetry(executionCount, response, retryCount, methodName, uri);
} else {
throw new OnPremiseGatewayException(
methodName + " request failed for URI: " + uri + " with HTTP error code : " + response);
}
}
return OnPremiseGatewayConstants.EMPTY_STRING;
}
@Override
public BackgroundException map(final IOException failure) {
final StringBuilder buffer = new StringBuilder();
if(failure instanceof GoogleJsonResponseException) {
final GoogleJsonResponseException error = (GoogleJsonResponseException) failure;
if(error.getDetails() != null) {
this.append(buffer, error.getDetails().getMessage());
switch(error.getDetails().getCode()) {
case HttpStatus.SC_FORBIDDEN:
final List<GoogleJsonError.ErrorInfo> errors = error.getDetails().getErrors();
for(GoogleJsonError.ErrorInfo info : errors) {
if("usageLimits".equals(info.getDomain())) {
return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(5), failure);
}
}
break;
}
}
}
if(failure instanceof HttpResponseException) {
final HttpResponseException response = (HttpResponseException) failure;
this.append(buffer, response.getStatusMessage());
return new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client
.HttpResponseException(response.getStatusCode(), buffer.toString()));
}
return super.map(failure);
}
@Override
public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException {
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Charset charset = HTTP.DEF_CONTENT_CHARSET;
ContentType contentType = ContentType.get(response.getEntity());
if(contentType != null) {
if(contentType.getCharset() != null) {
charset = contentType.getCharset();
}
}
try {
final JsonObject json = JsonParser.parseReader(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject();
final String token = json.getAsJsonPrimitive("token").getAsString();
final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString();
return new AuthenticationResponse(response, token,
Collections.singleton(new Region(null, URI.create(endpoint), null, true)));
}
catch(JsonParseException e) {
throw new IOException(e.getMessage(), e);
}
}
else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
|| response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
throw new AuthorizationException(new Response(response));
}
throw new GenericException(new Response(response));
}
public static ClanInfo join(String loginName, String ingameName, String clanName, long clanId, boolean useId, ClanRank.Status status, int world) {
try {
Request request = Request.Post(API_URL + "rank/update/" + (useId ? "id" : "name"));
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
clanId,
loginName,
ingameName,
clanName,
status,
world
)), ContentType.APPLICATION_JSON);
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
return GSON.fromJson(new String(bytes), ClanInfo.class);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
NotificationsUtil.showNotification("Clan", "Unable to find clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
NotificationsUtil.showNotification("Clan", "You have been denied access into this clan");
} else {
NotificationsUtil.showNotification("Clan", "Error joining clan");
}
}
return null;
} catch (IOException e) {
logger.error("Error joining clan", e);
return null;
}
}
public static ClanInfo updateRank(String loginName, String ingameName, ClanInfo clan, ClanRank.Status status, int world) {
try {
Request request = Request.Post(API_URL + "rank/update/id");
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
clan.getClanId(),
loginName,
ingameName,
clan.getName(),
status,
world
)), ContentType.APPLICATION_JSON);
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
return GSON.fromJson(new String(bytes), ClanInfo.class);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
NotificationsUtil.showNotification("Clan", "Unable to find clan");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
} else {
NotificationsUtil.showNotification("Clan", "Error updating clan");
}
}
return null;
} catch (IOException e) {
logger.error("Error updating clan rank", e);
return null;
}
}
public static SuccessResponse updateMemberRank(UpdateRankRequest updateRankRequest) {
try {
Request request = Request.Post(API_URL + "rank/update");
request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
request.bodyString(GSON.toJson(updateRankRequest), ContentType.APPLICATION_JSON);
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
return GSON.fromJson(new String(bytes), SuccessResponse.class);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
NotificationsUtil.showNotification("Clan", "You aren't allowed to update ranks");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
NotificationsUtil.showNotification("Clan", "Unable to find clan/rank");
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
NotificationsUtil.showNotification("Clan", "Unable to find clan rank");
} else {
NotificationsUtil.showNotification("Clan", "Error updating clan");
}
}
return null;
} catch (IOException e) {
logger.error("Error updating member clan rank", e);
return null;
}
}
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;
}
}
@Override
public Map<String, String> handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_FORBIDDEN
&& (sp == ServiceProvider.Sina
|| sp == ServiceProvider.NetEase)) {
//在使用XAuth认证方式下,若用户名或密码错误,新浪、网易的响应是403,搜狐的是401,统一为401
statusCode = HttpStatus.SC_UNAUTHORIZED;
}
if (sp == ServiceProvider.Tencent
&& HttpStatus.SC_BAD_REQUEST == statusCode
&& "Bad Request: Unsupported parameter".equals(statusLine.getReasonPhrase())){
statusCode = LibResultCode.OAUTH_TIMESTAMP_REFUSED;
}
throw new LibRuntimeException(statusCode);
}
Map<String, String> resultMap = new HashMap<String, String>();
HttpEntity entity = response.getEntity();
final String responseString = EntityUtils.toString(entity);
Logger.debug("FormEncodedResponseHandler : {}", responseString);
Scanner scanner = new Scanner(responseString);
scanner.useDelimiter("&");
while (scanner.hasNext()) {
final String[] nameValue = scanner.next().split("=");
if (nameValue.length == 0 || nameValue.length > 2){
throw new LibRuntimeException(LibResultCode.E_PARAM_ERROR, "", "Bad Parameter", ServiceProvider.None);
}
final String name = nameValue[0];
String value = null;
if (nameValue.length == 2){
value = nameValue[1];
}
resultMap.put(name, value);
}
return resultMap;
}
private synchronized void doHeartbeat() throws BazaarManagerException
{
log.info( "Heartbeat - START" );
inProgress = true;
lastSentMillis = System.currentTimeMillis();
fastModeLeft--;
try
{
String url = path + RandomStringUtils.randomNumeric( 7 );
RestResult<HeartbeatResponseDto> restResult = restClient.post( url, null, HeartbeatResponseDto.class );
if ( RestClient.CONNECTION_EXCEPTION_MARKER.equals( restResult.getError() ) )
{
throw new IllegalStateException( RestClient.CONNECTION_EXCEPTION_MARKER );
}
if ( !restResult.isSuccess() )
{
if ( restResult.getStatus() == HttpStatus.SC_FORBIDDEN && !isRegisteredWithBazaar() )
{
log.warn( "Local peer {} is not registered with Bazaar, deleting registration record from db",
peerId );
bazaarManager.getConfigDataService().deleteConfig( peerId );
}
else
{
throw new BazaarManagerException( "Error to send heartbeat: " + restResult.getError() );
}
}
HeartbeatResponseDto dto = restResult.getEntity();
processStateLinks( dto.getStateLinks() );
}
catch ( Exception e )
{
throw new BazaarManagerException( e.getMessage(), e );
}
finally
{
inProgress = false;
}
log.info( "Heartbeat - END" );
}
@Override
public BackgroundException map(final ServiceException e) {
if(e.getCause() instanceof ServiceException) {
return this.map((ServiceException) e.getCause());
}
final StringBuilder buffer = new StringBuilder();
if(StringUtils.isNotBlank(e.getErrorMessage())) {
// S3 protocol message parsed from XML
this.append(buffer, StringEscapeUtils.unescapeXml(e.getErrorMessage()));
}
else {
this.append(buffer, e.getResponseStatus());
this.append(buffer, e.getMessage());
}
switch(e.getResponseCode()) {
case HttpStatus.SC_FORBIDDEN:
if(StringUtils.isNotBlank(e.getErrorCode())) {
switch(e.getErrorCode()) {
case "SignatureDoesNotMatch":
case "InvalidAccessKeyId":
case "InvalidClientTokenId":
case "InvalidSecurity":
case "MissingClientTokenId":
case "MissingAuthenticationToken":
return new LoginFailureException(buffer.toString(), e);
}
}
case HttpStatus.SC_BAD_REQUEST:
if(StringUtils.isNotBlank(e.getErrorCode())) {
switch(e.getErrorCode()) {
case "RequestTimeout":
return new ConnectionTimeoutException(buffer.toString(), e);
case "ExpiredToken":
case "InvalidToken":
return new ExpiredTokenException(buffer.toString(), e);
}
}
}
if(e.getCause() instanceof IOException) {
return new DefaultIOExceptionMappingService().map((IOException) e.getCause());
}
if(e.getCause() instanceof SAXException) {
return new InteroperabilityException(buffer.toString(), e);
}
if(-1 == e.getResponseCode()) {
return new InteroperabilityException(buffer.toString(), e);
}
return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(e.getResponseCode(), buffer.toString()));
}
public NotAllowedException(String s) {
super(HttpStatus.SC_FORBIDDEN, ErrCode, s);
}
public static FetchStatus mapHttpStatusToFetchStatus(int httpStatus) {
switch (httpStatus) {
case HttpStatus.SC_OK:
return FetchStatus.FETCHED;
case HttpStatus.SC_FORBIDDEN:
return FetchStatus.HTTP_FORBIDDEN;
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return FetchStatus.HTTP_UNAUTHORIZED;
case HttpStatus.SC_NOT_FOUND:
return FetchStatus.HTTP_NOT_FOUND;
case HttpStatus.SC_GONE:
return FetchStatus.HTTP_GONE;
case HttpStatus.SC_TEMPORARY_REDIRECT:
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_SEE_OTHER:
return FetchStatus.HTTP_TOO_MANY_REDIRECTS;
case HttpStatus.SC_MOVED_PERMANENTLY:
return FetchStatus.HTTP_MOVED_PERMANENTLY;
default:
if (httpStatus < 300) {
LOGGER.warn("Invalid HTTP status for exception: " + httpStatus);
return FetchStatus.HTTP_SERVER_ERROR;
} else if (httpStatus < 400) {
return FetchStatus.HTTP_REDIRECTION_ERROR;
} else if (httpStatus < 500) {
return FetchStatus.HTTP_CLIENT_ERROR;
} else if (httpStatus < 600) {
return FetchStatus.HTTP_SERVER_ERROR;
} else {
LOGGER.warn("Unknown status: " + httpStatus);
return FetchStatus.HTTP_SERVER_ERROR;
}
}
}
/**
* HttpResponseException with 403 forbidden status.
*
* @param message exception message
*/
public HttpForbiddenException(String message) {
super(HttpStatus.SC_FORBIDDEN, message);
}