Java Code Examples for java.net.http.HttpResponse#statusCode()

The following examples show how to use java.net.http.HttpResponse#statusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleHttpClient.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: GitHub.java    From jmbe with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: ExternalMessageSignerService.java    From teku with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 4
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
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);
  }
}
 
Example 5
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 6
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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());
	}
}
 
Example 7
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 8
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 9
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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());
	}
}
 
Example 10
Source File: SimpleScheduledHandler.java    From blog-tutorials with MIT License 5 votes vote down vote up
@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;
}
 
Example 11
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: SimpleHttpClient.java    From tcMenu with Apache License 2.0 5 votes vote down vote up
@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();

}
 
Example 13
Source File: MavenRepositoryClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 14
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
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);
  }
}
 
Example 15
Source File: OreKitDataClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
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);
	}
}
 
Example 16
Source File: RestClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public void login(String username, String password) {
	HttpResponse<String> response = loginWithResponse(username, password);
	if (response.statusCode() != 200) {
		throw new RuntimeException("unable to login");
	}
}
 
Example 17
Source File: RestClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public void saveR2CloudConfiguration(String apiKey, boolean syncSpectogram) {
	HttpResponse<String> response = saveR2CloudConfigurationWithResponse(apiKey, syncSpectogram);
	if (response.statusCode() != 200) {
		LOG.info("status code: {}", response.statusCode());
	}
}
 
Example 18
Source File: RestClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public void resetPassword(String username) {
	HttpResponse<String> response = resetPasswordWithResponse(username);
	if (response.statusCode() != 200) {
		throw new RuntimeException("invalid status code: " + response.statusCode());
	}
}
 
Example 19
Source File: RestClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public void setGeneralConfiguration(GeneralConfiguration config) {
	HttpResponse<String> response = setGeneralConfigurationWithResponse(config);
	if (response.statusCode() != 200) {
		throw new RuntimeException("invalid status code: " + response.statusCode());
	}
}
 
Example 20
Source File: FileDownloadManager.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
private boolean callSuccessful(HttpResponse<?> response) {
    return response.statusCode() >= 200 && response.statusCode() < 300;
}