本文整理汇总了Java中org.apache.http.HttpStatus.SC_CREATED属性的典型用法代码示例。如果您正苦于以下问题:Java HttpStatus.SC_CREATED属性的具体用法?Java HttpStatus.SC_CREATED怎么用?Java HttpStatus.SC_CREATED使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类org.apache.http.HttpStatus
的用法示例。
在下文中一共展示了HttpStatus.SC_CREATED属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: register
private void register(RegisterModel model) throws Exception {
String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register";
String param = new Gson().toJson(model);
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type","application/json");
post.setEntity(new StringEntity(param));
CloseableHttpClient client = HttpClientBuilder.create().build();
// send the post request
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay());
} else {
logger.warn("Register message sent failed. Verify below information.");
logger.warn("[URL] : " + url);
logger.warn("[Message] : " + param);
logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8"));
}
}
示例2: postRecommendationReaction
public static boolean postRecommendationReaction(@NotNull String lessonId, @NotNull String user, int reaction) {
final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.RECOMMENDATION_REACTIONS_URL);
final String json = new Gson()
.toJson(new StepicWrappers.RecommendationReactionWrapper(new StepicWrappers.RecommendationReaction(reaction, user, lessonId)));
post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return false;
setTimeout(post);
try {
final CloseableHttpResponse execute = client.execute(post);
final int statusCode = execute.getStatusLine().getStatusCode();
final HttpEntity entity = execute.getEntity();
final String entityString = EntityUtils.toString(entity);
EntityUtils.consume(entity);
if (statusCode == HttpStatus.SC_CREATED) {
return true;
}
else {
LOG.warn("Stepic returned non-201 status code: " + statusCode + " " + entityString);
return false;
}
}
catch (IOException e) {
LOG.warn(e.getMessage());
return false;
}
}
示例3: postSubmission
private static void postSubmission(boolean passed, StepicWrappers.AttemptWrapper.Attempt attempt,
ArrayList<StepicWrappers.SolutionFile> files) throws IOException {
final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.SUBMISSIONS);
String requestBody = new Gson().toJson(new StepicWrappers.SubmissionWrapper(attempt.id, passed ? "1" : "0", files));
request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return;
final CloseableHttpResponse response = client.execute(request);
final HttpEntity responseEntity = response.getEntity();
final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
final StatusLine line = response.getStatusLine();
EntityUtils.consume(responseEntity);
if (line.getStatusCode() != HttpStatus.SC_CREATED) {
LOG.error("Failed to make submission " + responseString);
}
}
示例4: postHandle
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
final Object o, final ModelAndView modelAndView) throws Exception {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
return;
}
final boolean recordEvent = response.getStatus() != HttpStatus.SC_CREATED
&& response.getStatus() != HttpStatus.SC_OK;
if (recordEvent) {
LOGGER.debug("Recording submission failure for [{}]", request.getRequestURI());
recordSubmissionFailure(request);
}
}
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:15,代码来源:AbstractThrottledSubmissionHandlerInterceptorAdapter.java
示例5: doDeactivate
private ReplicationResult doDeactivate(TransportContext ctx, ReplicationTransaction tx, RestClient restClient) throws ReplicationException, JSONException, IOException {
ReplicationLog log = tx.getLog();
ObjectMapper mapper = new ObjectMapper();
IndexEntry content = mapper.readValue(tx.getContent().getInputStream(), IndexEntry.class);
Response deleteResponse = restClient.performRequest(
"DELETE",
"/" + content.getIndex() + "/" + content.getType() + "/" + DigestUtils.md5Hex(content.getPath()),
Collections.<String, String>emptyMap());
LOG.debug(deleteResponse.toString());
log.info(getClass().getSimpleName() + ": Delete Call returned " + deleteResponse.getStatusLine().getStatusCode() + ": " + deleteResponse.getStatusLine().getReasonPhrase());
if (deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED || deleteResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ReplicationResult.OK;
}
LOG.error("Could not delete " + content.getType() + " at " + content.getPath());
return new ReplicationResult(false, 0, "Replication failed");
}
示例6: CreateUserDataWithNP
@SuppressWarnings("unchecked")
private void CreateUserDataWithNP(int expectedSC, JSONObject bodyNp) {
// リクエストボディを設定
JSONObject body = new JSONObject();
body.put("__id", userDataId);
body.put("dynamicProperty", "dynamicPropertyValue");
createUserData(body, HttpStatus.SC_CREATED);
TResponse response = createUserDataWithNP(userDataId, bodyNp, expectedSC);
if (expectedSC == HttpStatus.SC_CREATED) {
// 登録データを一件取得し、レスポンスヘッダからETAGを取得する
TResponse getres = getUserData("testcell1", "box1", "setodata", navPropName,
userDataNpId, PersoniumUnitConfig.getMasterToken(), "", HttpStatus.SC_OK);
String etag = getres.getHeader(HttpHeaders.ETAG);
// レスポンスヘッダーのチェック
String location = UrlUtils.userData(cellName, boxName, colName, navPropName
+ "('" + userDataNpId + "')");
ODataCommon.checkCommonResponseHeader(response, location);
// レスポンスボディーのチェック
String nameSpace = getNameSpace(navPropName);
ODataCommon.checkResponseBody(response.bodyAsJson(), location, nameSpace, bodyNp, null, etag);
}
}
示例7: accountAuth
/**
* 正しい認証情報を使用してread_write権限があるコレクションに対して$batchをした場合処理が受付けられること.
* batchの実行順
* 1.POST(登録)
* 2.GET(一覧取得)
* 3.GET(取得)
* 4.PUT(更新)
* 5.DELETE(削除)
*/
@Test
public final void 正しい認証情報を使用してread_write権限があるコレクションに対して$batchをした場合処理が受付けられること() {
// 認証トークン取得
String[] tokens = accountAuth();
// ACL設定
DavResourceUtils.setACL(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK, COL_NAME, ACL_AUTH_TEST_FILE, BOX_NAME, "");
// READとWRITE→全てOK
TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
tokens[READ_WRITE], HttpStatus.SC_ACCEPTED);
// 期待するレスポンスコード
int[] expectedCodes = new int[] {HttpStatus.SC_CREATED,
HttpStatus.SC_OK,
HttpStatus.SC_OK,
HttpStatus.SC_NO_CONTENT,
HttpStatus.SC_NO_CONTENT };
// レスポンスボディのチェック(ステータス)
checkBatchResponseBody(res, expectedCodes);
}
示例8: checkBatchResponseBody
/**
* 不正な認証情報を使用してすべてのユーザがwrite可能なコレクションに対して$batchをした場合処理が受付けられること.
* batchの実行順
* 1.POST(登録)
* 2.GET(一覧取得)
* 3.GET(取得)
* 4.PUT(更新)
* 5.DELETE(削除)
*/
@Test
public final void 不正な認証情報を使用してすべてのユーザがwrite可能なコレクションに対して$batchをした場合処理が受付けられること() {
// 認証トークン取得
String invalidToken = "invalid token";
// ACL設定
String path = String.format("%s/%s/%s", TEST_CELL1, BOX_NAME, COL_NAME);
DavResourceUtils.setACLPrincipalAll(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK,
path, "<D:write />", "");
// READ→OK WRITE→403
TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
invalidToken, HttpStatus.SC_ACCEPTED);
// 期待するレスポンスコード
int[] expectedCodes = new int[] {HttpStatus.SC_CREATED,
HttpStatus.SC_FORBIDDEN,
HttpStatus.SC_FORBIDDEN,
HttpStatus.SC_NO_CONTENT,
HttpStatus.SC_NO_CONTENT };
// レスポンスボディのチェック(ステータス)
checkBatchResponseBody(res, expectedCodes);
}
示例9: JSONObject
/**
* 存在しないToRelationを指定した場合Message送信が失敗すること.
*/
@SuppressWarnings("unchecked")
@Test
public final void 存在しないToRelationを指定した場合Message送信が失敗すること() {
// リクエストボディ作成
JSONObject body = new JSONObject();
body.put("BoxBound", false);
body.put("InReplyTo", null);
body.put("ToRelation", "norelation");
body.put("Type", TYPE_MESSAGE);
body.put("Title", "title");
body.put("Body", "body");
body.put("Priority", 3);
body.put("RequestRelation", null);
body.put("RequestRelationTarget", null);
TResponse response = null;
try {
// メッセージ送信
response = SentMessageUtils.sent(MASTER_TOKEN_NAME, TEST_CELL1,
body.toJSONString(), HttpStatus.SC_BAD_REQUEST);
// エラーメッセージチェック
String code = PersoniumCoreException.SentMessage.TO_RELATION_NOT_FOUND_ERROR.getCode();
String message = PersoniumCoreException.SentMessage.TO_RELATION_NOT_FOUND_ERROR.params(
"norelation").getMessage();
checkErrorResponse(response.bodyAsJson(), code, message);
} finally {
if (response.getStatusCode() == HttpStatus.SC_CREATED) {
deleteOdataResource(response.getLocationHeader());
}
}
}
示例10: JSONObject
/**
* $batchでNavPro経由でのGETができないこと.
*/
@Test
@SuppressWarnings("unchecked")
public final void $batchでNavPro経由でのGETができないこと() {
try {
JSONObject srcBody = new JSONObject();
srcBody.put("__id", "srcKey");
srcBody.put("Name", "key0001");
super.createUserData(srcBody, HttpStatus.SC_CREATED, cellName, boxName, colName, "Sales");
String body = START_BOUNDARY
+ retrieveListBody("Sales('srcKey')/_Product")
+ START_BOUNDARY + retrievePostBody("Sales('srcKey')/_Product('id0001')", "id0001")
+ START_BOUNDARY + retrieveGetBody("Sales('srcKey')/_Product('id0001')")
+ START_BOUNDARY + retrievePutBody("Sales('srcKey')/_Product('id0001')")
+ START_BOUNDARY + retrieveDeleteBody("Sales('srcKey')/_Product('id0001')")
+ END_BOUNDARY;
TResponse response = 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()
.debug()
.statusCode(HttpStatus.SC_ACCEPTED);
// レスポンスボディのチェック
String expectedBody = START_BOUNDARY
+ retrieveQueryOperationResErrorBody(HttpStatus.SC_NOT_IMPLEMENTED)
+ START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
+ START_BOUNDARY + retrieveQueryOperationResErrorBody(HttpStatus.SC_BAD_REQUEST)
+ START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
+ START_BOUNDARY + retrieveChangeSetResErrorBody(HttpStatus.SC_BAD_REQUEST)
+ END_BOUNDARY;
checkBatchResponseBody(response, expectedBody);
} finally {
deleteUserData(cellName, boxName, colName, "Sales", "srcKey", PersoniumUnitConfig.getMasterToken(), -1);
}
}
示例11: postUnit
public static void postUnit(int lessonId, int position, int sectionId, Project project) {
if (!checkIfAuthorized(project, "postTask")) return;
final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.UNITS);
final StepicWrappers.UnitWrapper unitWrapper = new StepicWrappers.UnitWrapper();
final StepicWrappers.Unit unit = new StepicWrappers.Unit();
unit.setLesson(lessonId);
unit.setPosition(position);
unit.setSection(sectionId);
unitWrapper.setUnit(unit);
String requestBody = new Gson().toJson(unitWrapper);
request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
try {
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return;
final CloseableHttpResponse response = client.execute(request);
final HttpEntity responseEntity = response.getEntity();
final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
final StatusLine line = response.getStatusLine();
EntityUtils.consume(responseEntity);
if (line.getStatusCode() != HttpStatus.SC_CREATED) {
LOG.error(FAILED_TITLE + responseString);
showErrorNotification(project, FAILED_TITLE, responseString);
}
}
catch (IOException e) {
LOG.error(e.getMessage());
}
}
示例12: cellDelete
/**
* テストで作成したセルを削除する.
* @param response DcResponseオブジェクト
*/
public void cellDelete(PersoniumResponse response) {
if (response.getStatusCode() == HttpStatus.SC_CREATED) {
// 作成したCellのIDを抽出
String cellId = response.getResponseHeaders(HttpHeaders.LOCATION)[0].getValue().split("'")[1];
// CellのURL文字列を生成
// 本来は、LOCATIONヘッダにURLが格納されているが、jerseyTestFrameworkに向け直すため、再構築する
StringBuilder cellUrl = new StringBuilder(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME, cellId));
// Cellを削除
PersoniumResponse resDel = restDelete(cellUrl.toString());
assertEquals(HttpStatus.SC_NO_CONTENT, resDel.getStatusCode());
}
}
示例13: createWebDavCollectionWithDelete
/**
* MKCOLを実行し、作成に成功していれば削除する.
* @param token トークン
* @param code 期待するレスポンスコード
* @param path 対象のコレクションのパス
* @param cellName セル名
*/
public static void createWebDavCollectionWithDelete(String token, int code, String path, String cellName) {
TResponse res = createWebDavCollection(token, code, path);
if (res.getStatusCode() == HttpStatus.SC_CREATED) {
// コレクションの削除
ResourceUtils.delete("box/delete-col.txt", cellName, AbstractCase.MASTER_TOKEN_NAME,
HttpStatus.SC_NO_CONTENT, path);
}
}
示例14: doMultiPart
/**
* Executes MultiPart upload request to an endpoint with provided headers.
*
* @param uri
* endpoint that needs to be hit
* @param file
* file to be uploaded
* @param headers
* Key Value pair of headers
* @return Response Body after executing Multipart
* @throws StockException
* if api doesnt return with success code or when null/empty
* endpoint is passed in uri
*/
public static String doMultiPart(final String uri, final byte[] file,
final Map<String, String> headers) throws StockException {
if (sHttpClient == null) {
sHttpClient = HttpUtils.initialize();
}
HttpResponse response = null;
String responseBody = null;
if (uri == null || uri.isEmpty()) {
throw new StockException(-1, "URI cannot be null or Empty");
}
HttpPost request = new HttpPost(uri);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
if (file != null) {
String contentType = URLConnection.guessContentTypeFromStream(
new ByteArrayInputStream(file));
builder.addBinaryBody("similar_image", file,
ContentType.create(contentType), "file");
}
HttpEntity entity = builder.build();
request.setEntity(entity);
response = sHttpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
|| response.getStatusLine().getStatusCode()
== HttpStatus.SC_CREATED) {
responseBody = EntityUtils.toString(response.getEntity());
} else if (response.getStatusLine().getStatusCode()
/ HTTP_STATUS_CODE_DIVISOR
== HTTP_STATUS_CODE_API_ERROR) {
responseBody = EntityUtils.toString(response.getEntity());
throw new StockException(response.getStatusLine()
.getStatusCode(), responseBody);
} else if (response.getStatusLine().getStatusCode()
/ HTTP_STATUS_CODE_DIVISOR
== HTTP_STATUS_CODE_SERVER_ERROR) {
throw new StockException(response.getStatusLine()
.getStatusCode(), "API returned with Server Error");
}
} catch (StockException se) {
throw se;
} catch (Exception ex) {
throw new StockException(-1, ex.getMessage());
}
return responseBody;
}
示例15: postModule
private static int postModule(int courseId, int position, @NotNull final String title, Project project) {
final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/sections");
final StepicWrappers.Section section = new StepicWrappers.Section();
section.setCourse(courseId);
section.setTitle(title);
section.setPosition(position);
final StepicWrappers.SectionWrapper sectionContainer = new StepicWrappers.SectionWrapper();
sectionContainer.setSection(section);
String requestBody = new Gson().toJson(sectionContainer);
request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
try {
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return -1;
final CloseableHttpResponse response = client.execute(request);
final HttpEntity responseEntity = response.getEntity();
final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
final StatusLine line = response.getStatusLine();
EntityUtils.consume(responseEntity);
if (line.getStatusCode() != HttpStatus.SC_CREATED) {
LOG.error(FAILED_TITLE + responseString);
showErrorNotification(project, FAILED_TITLE, responseString);
return -1;
}
final StepicWrappers.Section
postedSection = new Gson().fromJson(responseString, StepicWrappers.SectionContainer.class).getSections().get(0);
return postedSection.getId();
}
catch (IOException e) {
LOG.error(e.getMessage());
}
return -1;
}