本文整理匯總了Java中org.apache.http.HttpStatus類的典型用法代碼示例。如果您正苦於以下問題:Java HttpStatus類的具體用法?Java HttpStatus怎麽用?Java HttpStatus使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpStatus類屬於org.apache.http包,在下文中一共展示了HttpStatus類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testConsumerInNonExistingQueue
import org.apache.http.HttpStatus; //導入依賴的package包/類
@Test
public void testConsumerInNonExistingQueue() throws Exception {
String queueName = "testConsumerInNonExistingQueue";
HttpGet httpGet = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
+ "/" + queueName + "/consumers");
CloseableHttpResponse response = client.execute(httpGet);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND,
"Incorrect status code");
String body = EntityUtils.toString(response.getEntity());
Error error = objectMapper.readValue(body, Error.class);
Assert.assertFalse(error.getMessage().isEmpty(), "Error message shouldn't be empty.");
}
示例2: isValidEndPoint
import org.apache.http.HttpStatus; //導入依賴的package包/類
@Override
public boolean isValidEndPoint(final URL url) {
Assert.notNull(this.httpClient);
HttpEntity entity = null;
try (final CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
final int responseCode = response.getStatusLine().getStatusCode();
for (final int acceptableCode : this.acceptableCodes) {
if (responseCode == acceptableCode) {
LOGGER.debug("Response code from server matched {}.", responseCode);
return true;
}
}
LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was {}",
responseCode);
if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
final String value = response.getStatusLine().getReasonPhrase();
LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}", url.toExternalForm(),
value);
}
entity = response.getEntity();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
EntityUtils.consumeQuietly(entity);
}
return false;
}
示例3: interruptibleGetRange
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* Gets a part of the given URL, writes the content into the given channel.
* Fails if the returned HTTP status is not "206 partial content".
*
* @param <IWC> a generic type for any class that implements InterruptibleChannel and WritableByteChannel
* @param url to get
* @param output written with the content of the HTTP response
* @param etag value of the If-Range header
* @param range_start range byte start (inclusive)
* @param range_end range byte end (inclusive)
*
* @return a response (contains the HTTP Headers, the status code, ...)
*
* @throws IOException IO error
* @throws InterruptedException interrupted
* @throws RuntimeException containing the actual exception if it is not an instance of IOException
*/
public <IWC extends InterruptibleChannel & WritableByteChannel>
HttpResponse interruptibleGetRange(String url, final IWC output, String etag, long range_start, long range_end)
throws IOException, InterruptedException
{
HttpGet get = new HttpGet(url);
get.setHeader("If-Range", etag);
get.setHeader("Range", String.format("bytes=%d-%d", range_start, range_end));
// This validator throws an IOException if the response code is not 206 partial content
ResponseValidator val = new ResponseValidator()
{
@Override
public void validate(HttpResponse response) throws HttpException, IOException
{
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
{
throw new IOException("Range request does not return partial content");
}
}
};
return interruptibleRequest(get, output, val);
}
示例4: createDavCollection
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* WebDAVにGETを指定してXHR2ヘッダーのALLOW_ORIGINのみ返卻されること.
*/
@Test
public final void WebDAVにGETを指定してXHR2ヘッダーのALLOW_ORIGINのみ返卻されること() {
try {
// コレクションの作成
createDavCollection();
TResponse response =
Http.request("crossdomain/xhr2-preflight-no-access-control-allow-headers.txt")
.with("path", "/testcell1/box1/davcol/test.txt")
.with("token", PersoniumUnitConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_NOT_FOUND)
.debug();
checkXHR2HeaderOnlyOrigin(response);
} finally {
// コレクションの削除
deleteDavCollection();
}
}
示例5: testValidationFilterFailedNull
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* Check the JAX-RS validation reject the null object in POST
*/
@Test
public void testValidationFilterFailedNull() throws IOException {
final HttpPost httppost = new HttpPost(BASE_URI + RESOURCE);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader(ACCEPT_LANGUAGE, "EN");
final HttpResponse response = httpclient.execute(httppost);
Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
Assert.assertNotNull(content);
@SuppressWarnings("all")
final Map<String, Map<String, List<Map<String, Object>>>> result = (Map<String, Map<String, List<Map<String, Object>>>>) new ObjectMapperTrim()
.readValue(content, HashMap.class);
Assert.assertFalse(result.isEmpty());
final Map<String, List<Map<String, Object>>> errors = result.get("errors");
Assert.assertNotNull(errors);
Assert.assertEquals(1, errors.size());
log.info("### ENTRY ####" + errors.keySet().iterator().next());
Assert.assertNotNull(errors.get("wine"));
Assert.assertEquals(1, ((List<?>) errors.get("wine")).size());
Assert.assertEquals(1, ((Map<?, ?>) ((List<?>) errors.get("wine")).get(0)).size());
Assert.assertEquals(((Map<?, ?>) ((List<?>) errors.get("wine")).get(0)).get(RULE), "NotNull");
}
示例6: setAcl
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* 親コレクションにread権限がある_かつ_対象ファイルにread権限があるアカウントでファイルの取得ができること.
* @throws JAXBException ACLのパース失敗
*/
@Test
public void 親コレクションにread権限がある_かつ_対象ファイルにread権限があるアカウントでファイルの取得ができること() throws JAXBException {
String token;
String path = String.format("%s/%s", PARENT_COL_NAME, TARGET_FILE_NAME);
// ACL設定
setAcl(PARENT_COL_NAME, ROLE, "read");
setAcl(path, ROLE, "read");
// アクセストークン取得
token = getToken(ACCOUNT);
// リクエスト実行
DavResourceUtils.getWebDav(CELL_NAME, token, BOX_NAME, path, HttpStatus.SC_OK);
}
示例7: getResponseMessage
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* レスポンスコードの説明を取得する.
* @return レスポンスコードの説明(例:OK, No Content)
*/
public String getResponseMessage() {
String message = null;
switch (this.responseCode) {
case HttpStatus.SC_NO_CONTENT:
message = "No Content";
break;
case HttpStatus.SC_CREATED:
message = "Created";
break;
case HttpStatus.SC_OK:
message = "OK";
break;
default:
message = "";
break;
}
return message;
}
示例8:
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* $skipに空文字を指定してUserDataの一覧をした場合に400エラーとなること.
*/
@Test
public final void $skipに空文字を指定してUserDataの一覧をした場合に400エラーとなること() {
// ユーザデータの一覧取得
TResponse res = Http.request("box/odatacol/list.txt")
.with("cell", cellName)
.with("box", boxName)
.with("collection", colName)
.with("entityType", entityTypeName)
.with("query", "?\\$skip=")
.with("accept", MediaType.APPLICATION_JSON)
.with("token", PersoniumUnitConfig.getMasterToken())
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.debug();
ODataCommon.checkErrorResponseBody(res, PersoniumCoreException.OData.QUERY_PARSE_ERROR_WITH_PARAM.getCode(),
PersoniumCoreException.OData.QUERY_PARSE_ERROR_WITH_PARAM.params("$skip").getMessage());
}
示例9:
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* $batchの登録で不正フォーマットのデータを指定した場合に400が返卻されること.
*/
@Test
public final void $batchの登録で不正フォーマットのデータを指定した場合に400が返卻されること() {
String body = START_BOUNDARY;
String code = PersoniumCoreException.OData.BATCH_BODY_PARSE_ERROR.getCode();
String err = PersoniumCoreException.OData.BATCH_BODY_PARSE_ERROR.getMessage();
Http.request("box/odatacol/batch.txt")
.with("cell", cellName)
.with("box", boxName)
.with("collection", colName)
.with("boundary", BOUNDARY)
.with("token", PersoniumUnitConfig.getMasterToken())
.with("body", body)
.returns()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.checkErrorResponse(code, err);
}
示例10: request
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* .
*/
@Test
public final void セル一括削除時にX_PERSONIUM_Recursiveヘッダにfalseを指定して412が返卻されること() {
// セルを作成する
String cellName = "CellBulkDeletionTest";
CellUtils.create(cellName, MASTER_TOKEN_NAME, -1);
// セルの一括削除APIを実行する
PersoniumRequest request = PersoniumRequest.delete(UrlUtils.cellRoot(cellName));
request.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN)
.header("X-Personium-Recursive", "false");
PersoniumResponse response = request(request);
// セル削除APIを実行して、412が返卻されることを確認
try {
assertEquals(HttpStatus.SC_PRECONDITION_FAILED, response.getStatusCode());
ODataCommon.checkErrorResponseBody(response, PersoniumCoreException.Misc.PRECONDITION_FAILED.getCode(),
PersoniumCoreException.Misc.PRECONDITION_FAILED
.params(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE)
.getMessage());
} finally {
// セルを削除する
request.header("X-Personium-Recursive", "true");
request(request);
}
}
示例11: afterCell
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* testの後に実行する.
*/
@After
public final void afterCell() {
PersoniumResponse res = null;
if (this.cellInfo.cellId != null) {
if (this.cellInfo.boxName != null) {
// テストBox 削除
res = restDelete(UrlUtils.cellCtl(this.cellInfo.cellName, Box.EDM_TYPE_NAME, this.cellInfo.boxName));
}
// テストCell 削除
res = restDelete(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME, this.cellInfo.cellId));
// レスポンスコードのチェック
if ((res.getStatusCode() == HttpStatus.SC_NO_CONTENT)
|| (res.getStatusCode() == HttpStatus.SC_OK)) {
this.cellInfo.initial();
}
assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode());
}
}
示例12: requesttoMypassword
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* ユニットローカルユニットユーザトークン認証でパスワード変更を実行し403が返ること.
* @throws TokenParseException 認証用トークンのパースエラー
*/
@Test
@Ignore // UUT promotion setting API invalidation.
public final void ユニットローカルユニットユーザトークン認証でパスワード変更を実行し403が返ること() throws TokenParseException {
// 認証
// アカウントにユニット昇格権限付與
DavResourceUtils.setProppatch(Setup.TEST_CELL1, MASTER_TOKEN,
"cell/proppatch-uluut.txt", HttpStatus.SC_MULTI_STATUS);
// パスワード認証でのユニット昇格
TResponse tokenResponse = Http.request("authnUnit/password-uluut.txt")
.with("remoteCell", Setup.TEST_CELL1)
.with("username", "account1")
.with("password", "password1")
.returns()
.statusCode(HttpStatus.SC_OK);
JSONObject json = tokenResponse.bodyAsJson();
String uluut = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN);
// ユニットローカルユニットユーザトークンを取得する
PersoniumResponse res = requesttoMypassword(uluut, "password3", Setup.TEST_CELL1);
assertEquals(403, res.getStatusCode());
}
示例13: testJaxRS405Error
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* @see ExceptionMapperResource#throwWebApplication()
*/
@Test
public void testJaxRS405Error() throws IOException {
final HttpGet httpget = new HttpGet(BASE_URI + RESOURCE + "/jax-rs");
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
Assert.assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, response.getStatusLine().getStatusCode());
final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class);
Assert.assertEquals("internal", result.get("code"));
Assert.assertNull(result.get("cause"));
Assert.assertEquals("HTTP 405 Method Not Allowed", result.get("message"));
} finally {
if (response != null) {
response.getEntity().getContent().close();
}
}
}
示例14: assertEquals
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* デフォルトログが存在しないときにファイルに対するGETで200が返卻されること.
*/
@Test
public final void デフォルトログが存在しないときにファイルに対するGETで200が返卻されること() {
try {
// Cell作成
CellUtils.create("TestCellForLogNotFound", MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
TResponse response = Http.request("cell/log-get.txt")
.with("METHOD", HttpMethod.GET)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("cellPath", "TestCellForLogNotFound")
.with("collection", CURRENT_COLLECTION)
.with("fileName", DEFAULT_LOG)
.with("ifNoneMatch", "*")
.returns();
response.debug();
response.statusCode(HttpStatus.SC_OK);
String responseBody = response.getBody();
// 空のレスポンスボディが返されることを確認
assertEquals(0, responseBody.length());
} finally {
// Cell削除
CellUtils.delete(MASTER_TOKEN_NAME, "TestCellForLogNotFound");
}
}
示例15: request
import org.apache.http.HttpStatus; //導入依賴的package包/類
/**
* ComplexTypePropertyの_ComplexTypeNameが半角英數字以外の場合_BadRequestが返卻されること.
*/
@Test
public final void ComplexTypePropertyの_ComplexTypeNameが半角英數字以外の場合_BadRequestが返卻されること() {
// リクエストパラメータ設定
PersoniumRequest req = PersoniumRequest.post(ComplexTypePropertyUtils.CTP_REQUEST_URL);
req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_NAME_KEY, CT_PROPERTY_NAME);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_COMPLEXTYPE_NAME_KEY, "Ad.*s");
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_TYPE_KEY,
EdmSimpleType.STRING.getFullyQualifiedTypeName());
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_NULLABLE_KEY, null);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_DEFAULT_VALUE_KEY, null);
req.addJsonBody(ComplexTypePropertyUtils.CT_PROPERTY_COLLECTION_KIND_KEY, null);
// リクエスト実行
PersoniumResponse response = request(req);
// レスポンスチェック
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode());
checkErrorResponse(
response.bodyAsJson(),
PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode(),
PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(
ComplexTypePropertyUtils.CT_PROPERTY_COMPLEXTYPE_NAME_KEY).getMessage());
}