下面列出了org.openqa.selenium.remote.http.HttpResponse#getStatus ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Result check() {
HttpRequest req = new HttpRequest(GET, "/status");
try {
HttpResponse res = client.execute(req);
if (res.getStatus() == 200) {
return new Result(true, externalUri + " is ok");
}
return new Result(
false,
String.format(
"An error occurred reading the status of %s: %s",
externalUri,
string(res)));
} catch (RuntimeException e) {
return new Result(
false,
"Unable to determine node status: " + e.getMessage());
}
}
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
// Try going upstream first. It's okay if this fails.
HttpRequest upReq = new HttpRequest(GET, String.format("/session/%s/log/types", session.getId()));
HttpResponse upRes = session.execute(upReq);
ImmutableSet.Builder<String> types = ImmutableSet.builder();
types.add(LogType.SERVER);
if (upRes.getStatus() == HTTP_OK) {
Map<String, Object> upstream = json.toType(string(upRes), Json.MAP_TYPE);
Object raw = upstream.get("value");
if (raw instanceof Collection) {
((Collection<?>) raw).stream().map(String::valueOf).forEach(types::add);
}
}
Response response = new Response(session.getId());
response.setValue(types.build());
response.setStatus(ErrorCodes.SUCCESS);
HttpResponse resp = new HttpResponse();
session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response);
return resp;
}
public static Optional<URI> getCdpEndPoint(
HttpClient.Factory clientFactory,
URI reportedUri) {
Require.nonNull("HTTP client factory", clientFactory);
Require.nonNull("DevTools URI", reportedUri);
ClientConfig config = ClientConfig.defaultConfig().baseUri(reportedUri);
HttpClient client = clientFactory.createClient(config);
HttpResponse res = client.execute(new HttpRequest(GET, "/json/version"));
if (res.getStatus() != HTTP_OK) {
return Optional.empty();
}
Map<String, Object> versionData = JSON.toType(string(res), MAP_TYPE);
Object raw = versionData.get("webSocketDebuggerUrl");
if (!(raw instanceof String)) {
return Optional.empty();
}
String debuggerUrl = (String) raw;
try {
return Optional.of(new URI(debuggerUrl));
} catch (URISyntaxException e) {
LOG.warning("Invalid URI for endpoint " + raw);
return Optional.empty();
}
}
private Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size) {
// Create the http request and send it
HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");
HttpResponse response;
long start = System.currentTimeMillis();
request.setHeader(CONTENT_LENGTH, String.valueOf(size));
request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
request.setContent(() -> newSessionBlob);
response = client.execute(request);
long time = System.currentTimeMillis() - start;
// Ignore the content type. It may not have been set. Strictly speaking we're not following the
// W3C spec properly. Oh well.
Map<?, ?> blob;
try {
blob = new Json().toType(string(response), Map.class);
} catch (JsonException e) {
throw new WebDriverException(
"Unable to parse remote response: " + string(response), e);
}
InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
time,
response.getStatus(),
blob);
return Stream.of(
new W3CHandshakeResponse().getResponseFunction(),
new JsonWireProtocolResponse().getResponseFunction())
.map(func -> func.apply(initialResponse))
.filter(Objects::nonNull)
.findFirst();
}
public void apply(ContainerId id) {
Require.nonNull("Container id", id);
HttpResponse res = client.execute(
new HttpRequest(DELETE, "/v1.40/containers/" + id)
.addHeader("Content-Length", "0")
.addHeader("Content-Type", "text/plain"));
if (res.getStatus() != HTTP_OK) {
LOG.warning("Unable to delete container " + id);
}
}
public static <T> T get(HttpResponse response, Type typeOfT) {
try (Reader reader = reader(response);
JsonInput input = JSON.newInput(reader)) {
// Alright then. We might be dealing with the object we expected, or we might have an
// error. We shall assume that a non-200 http status code indicates that something is
// wrong.
if (response.getStatus() != 200) {
throw ERRORS.decode(JSON.toType(string(response), MAP_TYPE));
}
if (Void.class.equals(typeOfT) && input.peek() == END) {
return null;
}
input.beginObject();
while (input.hasNext()) {
if ("value".equals(input.nextName())) {
return input.read(typeOfT);
} else {
input.skipValue();
}
}
throw new IllegalStateException("Unable to locate value: " + string(response));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Response decode(HttpResponse encodedResponse) {
String content = string(encodedResponse).trim();
log.fine(String.format(
"Decoding response. Response code was: %d and content: %s",
encodedResponse.getStatus(),
content));
String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));
Response response = new Response();
// Are we dealing with an error?
// {"error":"no such alert","message":"No tab modal was open when attempting to get the dialog text"}
if (HTTP_OK != encodedResponse.getStatus()) {
log.fine("Processing an error");
if (HTTP_BAD_METHOD == encodedResponse.getStatus()) {
response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
response.setValue(content);
} else {
Map<String, Object> obj = json.toType(content, MAP_TYPE);
Object w3cWrappedValue = obj.get("value");
if (w3cWrappedValue instanceof Map && ((Map<?, ?>) w3cWrappedValue).containsKey("error")) {
//noinspection unchecked
obj = (Map<String, Object>) w3cWrappedValue;
}
String message = "An unknown error has occurred";
if (obj.get("message") instanceof String) {
message = (String) obj.get("message");
}
String error = "unknown error";
if (obj.get("error") instanceof String) {
error = (String) obj.get("error");
}
response.setState(error);
response.setStatus(errorCodes.toStatus(error, Optional.of(encodedResponse.getStatus())));
// For now, we'll inelegantly special case unhandled alerts.
if ("unexpected alert open".equals(error) &&
HTTP_INTERNAL_ERROR == encodedResponse.getStatus()) {
String text = "";
Object data = obj.get("data");
if (data != null) {
Object rawText = ((Map<?, ?>) data).get("text");
if (rawText instanceof String) {
text = (String) rawText;
}
}
response.setValue(new UnhandledAlertException(message, text));
} else {
response.setValue(createException(error, message));
}
}
return response;
}
response.setState("success");
response.setStatus(ErrorCodes.SUCCESS);
if (!content.isEmpty()) {
if (contentType.startsWith("application/json") || Strings.isNullOrEmpty("")) {
Map<String, Object> parsed = json.toType(content, MAP_TYPE);
if (parsed.containsKey("value")) {
Object value = parsed.get("value");
response.setValue(value);
} else {
// Assume that the body of the response was the response.
response.setValue(json.toType(content, OBJECT_TYPE));
}
}
}
if (response.getValue() instanceof String) {
// We normalise to \n because Java will translate this to \r\n
// if this is suitable on our platform, and if we have \r\n, java will
// turn this into \r\r\n, which would be Bad!
response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
}
return response;
}