下面列出了java.net.http.HttpResponse#statusCode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private SimpleHttpClientCachedResponse callRemoteAndSaveResponse(HttpRequest request) throws IOException {
HttpResponse<InputStream> response = null;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
logInterruption(exception);
}
Path tempFile = null;
if (HttpUtils.callSuccessful(response)) {
InputStream body = response.body();
if (body != null) {
tempFile = Files.createTempFile("extension-out", ".tmp");
try (FileOutputStream out = new FileOutputStream(tempFile.toFile())) {
body.transferTo(out);
}
}
}
return new SimpleHttpClientCachedResponse(
HttpUtils.callSuccessful(response),
response.statusCode(),
response.headers().map(),
tempFile != null ? tempFile.toAbsolutePath().toString() : null);
}
/**
* Obtain the latest release object from the repository.
* @param repositoryURL for the GitHub api
* @return the latest release or null
*/
public static Release getLatestRelease(String repositoryURL)
{
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(repositoryURL)).build();
try
{
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if(response.statusCode() == 200)
{
return parseResponse(response.body());
}
else
{
mLog.error("Error while fetching latest releases - HTTP:" + response.statusCode());
}
}
catch(IOException | InterruptedException e)
{
mLog.error("Error while detecting the current release version of JMBE library", e);
}
return null;
}
private BLSSignature getBlsSignature(
final HttpResponse<String> response, final Throwable throwable) {
if (throwable != null) {
throw new ExternalSignerException(
"External signer failed to sign due to " + throwable.getMessage(), throwable);
}
if (response.statusCode() != 200) {
throw new ExternalSignerException(
"External signer failed to sign and returned invalid response status code: "
+ response.statusCode());
}
try {
final Bytes signature = Bytes.fromHexString(response.body());
return BLSSignature.fromBytes(signature);
} catch (final IllegalArgumentException e) {
throw new ExternalSignerException(
"External signer returned an invalid signature: " + e.getMessage(), e);
}
}
public void getUser() throws Exception {
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "?name=x"),
Optional.empty()
).GET().build();
HttpResponse<String> response = restClient.send(request);
LOG.info("Response status code: {}", response.statusCode());
LOG.info("Response headers: {}", response.headers());
LOG.info("Response body: {}", response.body());
if (response.statusCode() == 200) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserVO[] userVO = objectMapper.readValue(response.body(), UserVO[].class);
LOG.info("UserVO: {}", userVO.length);
}
}
public void getUser() throws Exception {
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "?name=x"),
Optional.empty()
).GET().build();
HttpResponse<String> response = restClient.send(request);
LOG.info("Response status code: {}", response.statusCode());
LOG.info("Response headers: {}", response.headers());
LOG.info("Response body: {}", response.body());
if (response.statusCode() == 200) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserVO[] userVO = objectMapper.readValue(response.body(), UserVO[].class);
LOG.info("UserVO: {}", userVO.length);
}
}
@Override
public Metadata metadata() {
try {
HttpRequest request = HttpRequest.newBuilder(withArtifactPath(apiUrl, id)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
if (response.statusCode() != 200)
throw new RuntimeException("Status code '" + response.statusCode() + "' and body\n'''\n" +
response.body() + "\n'''\nfor request " + request);
return Metadata.fromXml(response.body());
}
catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public byte[] postRequestForBinaryData(String url, String parameter,
HttpDataType reqDataType) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(20))
.header("Content-Type", toContentType(reqDataType))
.POST(HttpRequest.BodyPublishers.ofString(parameter))
.build();
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if(response.statusCode() != HTTP_SUCCESS) throw new IOException("Call returned bad status " + response.statusCode());
return response.body();
}
public JsonObject getObservation(String satelliteId, String observationId) {
HttpResponse<String> response = getObservationResponse(satelliteId, observationId);
if (response.statusCode() == 404) {
return null;
}
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
return (JsonObject) Json.parse(response.body());
}
@Override
public Void handleRequest(Void input, Context context) {
System.out.println("About to check availability of https://rieckpil.de");
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
try {
HttpRequest request = HttpRequest
.newBuilder(new URI("https://rieckpil.de"))
.timeout(Duration.ofSeconds(2))
.GET()
.build();
HttpResponse<String> result = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if(result.statusCode() != 200) {
// inform me via e.g. Slack or Telegram
} else {
System.out.println("Blog is up- and running");
}
}
catch (URISyntaxException | IOException | InterruptedException e) {
// inform me via e.g. Slack or Telegram
e.printStackTrace();
}
return null;
}
public void setup(String keyword, String username, String password) {
HttpResponse<String> response = setupWithResponse(keyword, username, password);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
}
public JsonObject updateSchedule(String id, boolean enabled) {
HttpResponse<String> response = updateScheduleWithResponse(id, enabled);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
return (JsonObject) Json.parse(response.body());
}
public String getFile(String url) {
HttpResponse<String> response = getFileResponse(url);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
return response.body();
}
public void scheduleComplete(String satelliteId) {
HttpResponse<String> response = scheduleCompleteResponse(satelliteId);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
}
public JsonObject requestObservationSpectogram(String satelliteId, String observationId) {
HttpResponse<String> response = requestObservationSpectogramResponse(satelliteId, observationId);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
return (JsonObject) Json.parse(response.body());
}
private void downloadAndSaveTo(String url, Path dst) throws IOException {
Path tempPath = dst.getParent().resolve(dst.getFileName() + ".tmp").normalize();
if (Files.exists(tempPath) && !Util.deleteDirectory(tempPath)) {
throw new RuntimeException("unable to delete tmp directory: " + tempPath);
}
Files.createDirectories(tempPath);
Builder result = HttpRequest.newBuilder().uri(URI.create(url));
result.timeout(Duration.ofMillis(TIMEOUT));
result.header("User-Agent", R2Cloud.getVersion() + " [email protected]");
HttpRequest request = result.build();
try {
HttpResponse<InputStream> response = httpclient.send(request, BodyHandlers.ofInputStream());
if (response.statusCode() != 200) {
throw new IOException("invalid status code: " + response.statusCode());
}
Optional<String> contentType = response.headers().firstValue("Content-Type");
if (contentType.isEmpty() || !contentType.get().equals("application/zip")) {
throw new IOException("Content-Type is empty or unsupported: " + contentType);
}
try (ZipInputStream zis = new ZipInputStream(response.body())) {
ZipEntry zipEntry = null;
while ((zipEntry = zis.getNextEntry()) != null) {
Path destFile = tempPath.resolve(zipEntry.getName()).normalize();
if (!destFile.startsWith(tempPath)) {
throw new IOException("invalid archive. zip slip detected: " + destFile);
}
if (zipEntry.isDirectory()) {
Files.createDirectories(destFile);
continue;
}
if (!Files.exists(destFile.getParent())) {
Files.createDirectories(destFile.getParent());
}
Files.copy(zis, destFile, StandardCopyOption.REPLACE_EXISTING);
}
Files.move(tempPath, dst, StandardCopyOption.REPLACE_EXISTING);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
public void login(String username, String password) {
HttpResponse<String> response = loginWithResponse(username, password);
if (response.statusCode() != 200) {
throw new RuntimeException("unable to login");
}
}
public void saveR2CloudConfiguration(String apiKey, boolean syncSpectogram) {
HttpResponse<String> response = saveR2CloudConfigurationWithResponse(apiKey, syncSpectogram);
if (response.statusCode() != 200) {
LOG.info("status code: {}", response.statusCode());
}
}
public void resetPassword(String username) {
HttpResponse<String> response = resetPasswordWithResponse(username);
if (response.statusCode() != 200) {
throw new RuntimeException("invalid status code: " + response.statusCode());
}
}
public void setGeneralConfiguration(GeneralConfiguration config) {
HttpResponse<String> response = setGeneralConfigurationWithResponse(config);
if (response.statusCode() != 200) {
throw new RuntimeException("invalid status code: " + response.statusCode());
}
}
private boolean callSuccessful(HttpResponse<?> response) {
return response.statusCode() >= 200 && response.statusCode() < 300;
}