這裏是我的代碼,我用來實現這一目標:
public enum HttpStatusCode {
UNKNOWN (-1 , false),
ACCEPTED (HttpStatus.SC_ACCEPTED , true), // 202
BAD_GATEWAY (HttpStatus.SC_BAD_GATEWAY , false), // 502
BAD_REQUEST (HttpStatus.SC_BAD_REQUEST , false), // 400
CONFLICT (HttpStatus.SC_CONFLICT , false), // 409
CREATED (HttpStatus.SC_CREATED , true), // 201
CONTINUE (HttpStatus.SC_CONTINUE , true), // 100
MOVED_TEMPORARILY (HttpStatus.SC_MOVED_TEMPORARILY , false), // 302
FORBIDDEN (HttpStatus.SC_FORBIDDEN , false), // 403
GATEWAY_TIMEOUT (HttpStatus.SC_GATEWAY_TIMEOUT , false), // 504
UNPROCESSABLE_ENTITY (HttpStatus.SC_UNPROCESSABLE_ENTITY , false); // 422
private final int value;
private final boolean name;
private HttpStatusCode(int value, boolean name) {
this.value = value;
this.name = name;
}
public boolean isOk() {
return name;
}
public int getErrorCode(){
return value;
}
public static HttpStatusCode getHttpStatusCode(int errorCode){
for (HttpStatusCode code : HttpStatusCode.values()) {
if(code.getErrorCode() == errorCode)
return code;
}
return HttpStatusCode.UNKNOWN;
}
}
這個我可以查詢這樣如果返回代碼是確定或不正常:
StringRequestEntity requestEntity = new StringRequestEntity(p.toString(),
"application/json",
"UTF-8");
mPost.setRequestEntity(requestEntity);
int status = client.executeMethod(mPost);
HttpStatusCode statusCode = HttpStatusCode.getHttpStatusCode(status);
// in case everything is fine, neo4j should return 200, 201 or 202. any other case needs to be investigated
if (!statusCode.isOk()){
logger.error(HttpErrorMessages.getHttpErrorText(statusCode.getErrorCode()));
}
也許可以幫助一些其他人也