下面列出了怎么用org.apache.http.client.HttpResponseException的API类实例代码及写法,或者点击链接到github查看源代码。
private void doPushImage(String url, Map<String, String> header, HcChunkedResponseHandlerWrapper handler, int status,
int retries) throws IOException {
// 0: The original attemp, 1..retry: possible retries.
for (int i = 0; i <= retries; i++) {
try {
delegate.post(url, null, header, handler, HTTP_OK);
return;
} catch (HttpResponseException e) {
if (isRetryableErrorCode(e.getStatusCode()) && i != retries) {
log.warn("failed to push image to [{}], retrying...", url);
} else {
throw e;
}
}
}
}
private JsonObject parseResponse(CloseableHttpResponse res) throws IOException {
try {
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
if (entity != null) {
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null)
charset = Charset.forName("UTF-8");
Reader reader = new InputStreamReader(entity.getContent(), charset);
return (JsonObject) new JsonParser().parse(reader);
}
// no response body
return new JsonObject();
}
else
throw new HttpResponseException(
res.getStatusLine().getStatusCode(),
res.getStatusLine().getReasonPhrase());
}
finally {
res.close();
}
}
/**
* Lists folder content.
*
* @param folder folder or <code>null</code>
* @return content response
* @throws URISyntaxException if invalid URL
* @throws IOException if accessing token fails
*/
public ContentResponse listContent(String folder) throws URISyntaxException, IOException {
String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).toASCIIString();
HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));
try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
if (httpResponse.getStatusLine().getStatusCode()>=400) {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
}
String responseContent = IOUtils.toString(contentStream, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
ContentResponse response = mapper.readValue(responseContent, ContentResponse.class);
response.url = url;
return response;
}
}
@BeforeClass
public static void initRealmAndUsers() throws IOException {
Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
clientBeforeChanges = keycloak.realms().realm("master").clients().findByClientId(CLIENT).get(0);
createTestUser("admin", "admin", "master", TEST_USER, "password", "user");
//just making sure realm is not already present
String token = keycloak.tokenManager().getAccessTokenString();
RealmRepresentation nullRealm = null;
try {
nullRealm = exportRealm(token, TEST_REALM_NAME);
} catch (HttpResponseException e) {
Assert.assertEquals(404, e.getStatusCode());
}
Assert.assertNull(nullRealm);
//end just making sure realm is not already present
}
protected T parseResponse(StatusLine statusLine, HttpEntity entity, Class<T> pojoClass)
throws IOException {
if (statusLine.getStatusCode() >= 400) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset() != null ? contentType.getCharset() :
StandardCharsets.UTF_8;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent(), charset))) {
return unmarshallContent(reader, pojoClass);
}
}
/**
* @inheritDoc
*/
@Override
public int updateFolder(String folderPath, Map<String, String> properties) throws IOException {
Set<PropertyValue> propertyValues = new HashSet<>();
if (properties != null) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
}
}
ExchangePropPatchRequest propPatchRequest = new ExchangePropPatchRequest(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues);
try (CloseableHttpResponse response = httpClientAdapter.execute(propPatchRequest)) {
propPatchRequest.handleResponse(response);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_MULTI_STATUS) {
try {
status = propPatchRequest.getResponseStatusCode();
} catch (HttpResponseException e) {
throw new IOException(e.getMessage(), e);
}
}
return status;
}
}
/**
* Reads item metadata.
* @param itemId item id
* @param format metadata format
* @param token token
* @return item metadata if available
* @throws URISyntaxException if invalid URL
* @throws IOException if operation fails
*/
public String readItemMetadata(String itemId, MetadataFormat format, String token) throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder(itemMetaUri(itemId));
builder.setParameter("format", (format != null ? format : MetadataFormat.DEFAULT).toString());
if (token!=null) {
builder.setParameter("token", token);
}
HttpGet req = new HttpGet(builder.build());
try {
return execute(req, 0);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 500) {
return null;
}
throw ex;
}
}
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
// do not process if request has been cancelled
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
byte[] responseBody;
responseBody = getResponseData(response.getEntity());
// additional cancellation check as getResponseData() can take non-zero time to process
if (!Thread.currentThread().isInterrupted()) {
if (status.getStatusCode() >= 300) {
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
}
}
@Test
public void testConvertMovie() throws AirtableException, HttpResponseException {
Table<Movie> movieTable = base.table("Movies", Movie.class);
Movie movie = movieTable.find("recFj9J78MLtiFFMz");
assertNotNull(movie);
assertEquals(movie.getId(),"recFj9J78MLtiFFMz");
assertEquals(movie.getName(),"The Godfather");
assertEquals(movie.getPhotos().size(),2);
assertEquals(movie.getDirector().size(),1);
assertEquals(movie.getActors().size(),2);
assertEquals(movie.getGenre().size(),1);
//TODO Test für Datum
}
@Test
public void testConvertAttachement() throws AirtableException, HttpResponseException {
Table<Movie> movieTable = base.table("Movies", Movie.class);
Movie movie = movieTable.find("recFj9J78MLtiFFMz");
assertNotNull(movie);
assertEquals(movie.getPhotos().size(),2);
Attachment photo1 = movie.getPhotos().get(0);
assertNotNull(photo1);
Attachment photo2 = movie.getPhotos().get(0);
assertNotNull(photo2);
assertEquals(photo1.getId(),"attk3WY5B28GVcFGU");
assertEquals(photo1.getUrl(),"https://dl.airtable.com/9UhUUeAtSym1PzBdA0q0_AlPacinoandMarlonBrando.jpg");
assertEquals(photo1.getFilename(),"AlPacinoandMarlonBrando.jpg");
assertEquals(photo1.getSize(),35698,0);
assertEquals(photo1.getType(),"image/jpeg");
assertEquals(photo1.getThumbnails().size(),2);
}
@GuardedBy("lock")
void authenticate(HttpClient client) throws IOException {
if (id == null || id.isEmpty() || password == null || password.isEmpty()) {
invalid = "Unable to re-authenticate expired token: missing appleId/ password.";
} else {
try {
Auth auth = Auth.from(client, id, password);
if (auth.dsPrsID().equals(token.auth().dsPrsID())) {
token = Token.from(auth);
} else {
logger.error("-- reauthentication() > mismatched dsPrsID: {} > {}",
token.auth().dsPrsID(), auth.dsPrsID());
invalid = "Unable to re-authenticate expired token: account mismatch.";
}
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
invalid = "Unable to re-authenticate expired token: invalid appleId/ password.";
}
}
}
testIsInvalid();
}
/**
* Delete the credential stored in the specified user's domain.
*
* @param userName jenkins user name
* @param domainName name of domain
* @param credentialId credentialId
* @throws IOException
*/
public void deleteUserDomainCredential(String userName, String domainName, String credentialId) throws IOException {
String path = "/user/" + userName + "/credentials/store/user/domain/" + domainName + "/credential/" + credentialId;
try {
client.post(path + "/doDelete", false);
logger.info("deleted credential at " + path);
} catch (HttpResponseException e) {
if (e.getStatusCode() == 404) {
logger.debug("received 404 while trying to delete credential at " + path);
} else {
logger.error("error deleting credential at " + path);
logger.error("message = " + e.getMessage());
throw e;
}
}
}
@Test
public void testSelectTableSorted() throws AirtableException, HttpResponseException {
Table table = base.table("Movies", Movie.class);
List<Movie> retval = table.select(new Sort("Name", Sort.Direction.asc));
assertNotNull(retval);
assertEquals(9, retval.size());
Movie mov = retval.get(0);
assertEquals("Billy Madison", mov.getName());
retval = table.select(new Sort("Name", Sort.Direction.desc));
assertNotNull(retval);
assertEquals(9, retval.size());
mov = retval.get(0);
assertEquals("You've Got Mail", mov.getName());
}
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
//already finished
if (!Thread.currentThread().isInterrupted())
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
} else if (status.getStatusCode() >= 300) {
if (!Thread.currentThread().isInterrupted())
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
if (!Thread.currentThread().isInterrupted()) {
Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
if (header == null) {
append = false;
current = 0;
} else {
Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
}
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
}
}
}
}
@Override
public DataContent fetchContent(UUID taskId, String recordId, SimpleCredentials credentials) throws DataInputException {
InputBroker broker = null;
try {
TaskDefinition taskDefinition = readTaskDefinition(taskId);
Task task = this.createTask(taskDefinition);
if (!task.getDataSource().hasAccess(credentials)) {
throw new HttpResponseException(HttpStatus.SC_UNAUTHORIZED, "Invalid credentials");
}
broker = newInputBroker(taskDefinition.getSource());
broker.initialize(new SimpleInitContext(task, new ArrayList<>()));
return broker.readContent(recordId);
} catch (InvalidDefinitionException|DataProcessorException|HttpResponseException ex) {
throw new DataInputException(broker, String.format("Error fetching content from: %s -> $s", taskId, recordId), ex);
} finally {
if (broker!=null) {
broker.terminate();
}
}
}
private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException, URISyntaxException {
try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) {
String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
String responseContent = IOUtils.toString(contentStream, "UTF-8");
LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));
if (httpResponse.getStatusLine().getStatusCode() >= 400) {
T value = null;
try {
value = mapper.readValue(responseContent, clazz);
} catch (Exception ex) {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
}
if (value == null) {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
}
return value;
}
return mapper.readValue(responseContent, clazz);
}
}
/**
* Generates token.
*
* @param minutes expiration in minutes.
* @param credentials credentials.
* @return token response
* @throws URISyntaxException if invalid URL
* @throws IOException if accessing token fails
*/
public TokenResponse generateToken(int minutes, SimpleCredentials credentials) throws URISyntaxException, IOException {
HttpPost post = new HttpPost(rootUrl.toURI().resolve("tokens/generateToken"));
HashMap<String, String> params = new HashMap<>();
params.put("f", "json");
if (credentials != null) {
params.put("username", StringUtils.trimToEmpty(credentials.getUserName()));
params.put("password", StringUtils.trimToEmpty(credentials.getPassword()));
}
params.put("client", "requestip");
params.put("expiration", Integer.toString(minutes));
HttpEntity entity = new UrlEncodedFormEntity(params.entrySet().stream()
.map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()));
post.setEntity(entity);
try (CloseableHttpResponse httpResponse = httpClient.execute(post); InputStream contentStream = httpResponse.getEntity().getContent();) {
if (httpResponse.getStatusLine().getStatusCode()>=400) {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
}
String responseContent = IOUtils.toString(contentStream, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(responseContent, TokenResponse.class);
}
}
private void doPushImage(String url, Map<String, String> header, HcChunkedResponseHandlerWrapper handler, int status,
int retries) throws IOException {
// 0: The original attemp, 1..retry: possible retries.
for (int i = 0; i <= retries; i++) {
try {
delegate.post(url, null, header, handler, HTTP_OK);
return;
} catch (HttpResponseException e) {
if (isRetryableErrorCode(e.getStatusCode()) && i != retries) {
log.warn("failed to push image to [{}], retrying...", url);
} else {
throw e;
}
}
}
}
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
// do not process if request has been cancelled
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
byte[] responseBody;
responseBody = getResponseData(response.getEntity());
// additional cancellation check as getResponseData() can take non-zero time to process
if (!Thread.currentThread().isInterrupted()) {
if (status.getStatusCode() >= 300) {
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
}
}
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
// do not process if request has been cancelled
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
byte[] responseBody;
responseBody = getResponseData(response.getEntity());
// additional cancellation check as getResponseData() can take non-zero time to process
if (!Thread.currentThread().isInterrupted()) {
if (status.getStatusCode() >= 300) {
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
}
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
/**
* Executes a HTTP GET request and returns the response string.
* @param uri The URI containing the request URL and request parameters.
* @return the HTTP response string after executing the GET request
*/
public static String executeGetRequest(URI uri) throws IOException {
HttpUriRequest request = new HttpGet(uri);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();
HttpResponse httpResponse = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.build()
.execute(request);
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "UTF-8");
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return response;
} else {
throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
}
}
private QueryResponse query(URIBuilder builder, HttpEntity entity) throws IOException, URISyntaxException {
if (cred != null && !cred.isEmpty()) {
builder = builder.addParameter("access_token", getAccessToken());
}
QueryResponse response = null;
try {
response = query(builder.build(), entity);
} catch (HttpResponseException ex) {
if (ex.getStatusCode() == 401) {
clearToken();
if (cred != null && !cred.isEmpty()) {
builder = builder.addParameter("access_token", getAccessToken());
}
response = query(builder.build(), entity);
} else {
throw ex;
}
}
return response;
}
private void givenThePushWillFail(final int retries) throws IOException {
new Expectations() {{
int fail = retries + 1;
mockDelegate.post(anyString, null, (Map<String, String>) any, (ResponseHandler) any, 200);
minTimes = fail; maxTimes = fail;
result = new HttpResponseException(HTTP_INTERNAL_ERROR, "error");
}};
}
@Override
public InputStream handleResponse(final HttpResponse response) throws IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
return entity == null ? null : entity.getContent();
}
/**
* Send post request to the {@link #getEndpointUrl()} with suffix as a url
* parameter.
*
* @param url
* suffix to the {@link #getEndpointUrl()}.
* @param parameters
* map of parameters that will be attached to the request
* @return response of the request
* @throws HttpResponseException
* @throws IOException
*/
protected String sendPostRequest(final String url, final Map<String, String> parameters)
throws HttpResponseException, IOException {
final HttpPost postRequest = new HttpPost(getEndpointUrl() + url);
final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(getTimeout()).build();
postRequest.setConfig(requestConfig);
postRequest.addHeader(getxCsrfToken(), getCsrfToken());
postRequest.setEntity(new UrlEncodedFormEntity(createParametersList(parameters)));
final HttpResponse response = getHttpClient().execute(postRequest, getContext());
final String responseBody = new BasicResponseHandler().handleResponse(response);
return responseBody;
}
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
StatusLine status = response.getStatusLine();
Header[] contentTypeHeaders = response.getHeaders("Content-Type");
if (contentTypeHeaders.length != 1) {
//malformed/ambiguous HTTP Header, ABORT!
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
return;
}
Header contentTypeHeader = contentTypeHeaders[0];
boolean foundAllowedContentType = false;
for (String anAllowedContentType : getAllowedContentTypes()) {
try {
if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
foundAllowedContentType = true;
}
} catch (PatternSyntaxException e) {
Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
}
}
if (!foundAllowedContentType) {
//Content-Type not in allowed list, ABORT!
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
return;
}
super.sendResponseMessage(response);
}
@Test
public void nonMasterAdminCantExportTestRealm() throws IOException {
try {
final String testAdminUser = "test.admin";
TestsHelper.importTestRealm("admin", "admin", "/" + TEST_REALM_NAME + "-realm.json");
createTestUser("admin", "admin", TEST_REALM_NAME, testAdminUser, "password", "user", "admin");
Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, TEST_REALM_NAME, testAdminUser, "password", CLIENT);
String token = keycloak.tokenManager().getAccessTokenString();
expectedEx.expect(HttpResponseException.class);
expectedEx.expect(hasProperty("statusCode", is(403)));
exportRealm(token, TEST_REALM_NAME);
} finally {
TestsHelper.deleteRealm("admin", "admin", TEST_REALM_NAME);
}
}
/**
* @inheritDoc
*/
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
Set<PropertyValue> propertyValues = new HashSet<>();
if (properties != null) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
}
}
propertyValues.add(Field.createPropertyValue("folderclass", folderClass));
// standard MkColMethod does not take properties, override ExchangePropPatchRequest instead
ExchangePropPatchRequest propPatchRequest = new ExchangePropPatchRequest(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues) {
@Override
public String getMethod() {
return "MKCOL";
}
};
int status;
try (CloseableHttpResponse response = httpClientAdapter.execute(propPatchRequest)) {
propPatchRequest.handleResponse(response);
status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_MULTI_STATUS) {
status = propPatchRequest.getResponseStatusCode();
} else if (status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
LOGGER.info("Folder " + folderPath + " already exists");
}
} catch (HttpResponseException e) {
throw new IOException(e.getMessage(), e);
}
LOGGER.debug("Create folder " + folderPath + " returned " + status);
return status;
}
/**
* Helper method that returns an error code from an http response
* @param t Throwable
* @return Integer representing error code
*/
private Integer getErrorCode(Throwable t){
Integer error = null;
if (t instanceof JsonEmbeddedException){
error = ((JsonEmbeddedException)t).getCode();
} else if (t instanceof HttpResponseException){
error= ((HttpResponseException) t).getStatusCode();
}
return error;
}