use of java.net.http.HttpClient in project jena by apache.
the class AbstractTestAuth_JDK method withAuthJDK.
public static UpdateExecutionHTTP withAuthJDK(UpdateExecutionHTTPBuilder builder, String user, String passwd) {
Authenticator authenticator = AuthLib.authenticator(user, passwd);
HttpClient hc = HttpClient.newBuilder().authenticator(authenticator).build();
return builder.httpClient(hc).build();
}
use of java.net.http.HttpClient in project jena by apache.
the class AbstractTestAuth_JDK method withAuthJDK.
public static QueryExecutionHTTP withAuthJDK(QueryExecutionHTTPBuilder builder, String user, String passwd) {
Authenticator authenticator = AuthLib.authenticator(user, passwd);
HttpClient hc = HttpClient.newBuilder().authenticator(authenticator).build();
return builder.httpClient(hc).build();
}
use of java.net.http.HttpClient in project MinecraftForge by MinecraftForge.
the class VersionChecker method startVersionCheck.
public static void startVersionCheck() {
new Thread("Forge Version Check") {
private HttpClient client;
@Override
public void run() {
if (!FMLConfig.runVersionCheck()) {
LOGGER.info("Global Forge version check system disabled, no further processing.");
return;
}
client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).build();
gatherMods().forEach(this::process);
}
/**
* Returns the response body as a String for the given URL while following redirects
*/
private String openUrlString(URL url) throws IOException, URISyntaxException, InterruptedException {
URL currentUrl = url;
for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++) {
var request = HttpRequest.newBuilder().uri(currentUrl.toURI()).timeout(Duration.ofSeconds(HTTP_TIMEOUT_SECS)).setHeader("Accept-Encoding", "gzip").GET().build();
final HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int responseCode = response.statusCode();
if (responseCode >= 300 && responseCode <= 399) {
String newLocation = response.headers().firstValue("Location").orElseThrow(() -> new IOException("Got a 3xx response code but Location header was null while trying to fetch " + url));
currentUrl = new URL(currentUrl, newLocation);
continue;
}
final boolean isGzipEncoded = response.headers().firstValue("Content-Encoding").orElse("").equals("gzip");
final String bodyStr;
try (InputStream inStream = isGzipEncoded ? new GZIPInputStream(response.body()) : response.body()) {
try (var bufferedReader = new BufferedReader(new InputStreamReader(inStream))) {
bodyStr = bufferedReader.lines().collect(Collectors.joining("\n"));
}
}
return bodyStr;
}
throw new IOException("Too many redirects while trying to fetch " + url);
}
private void process(IModInfo mod) {
Status status = PENDING;
ComparableVersion target = null;
Map<ComparableVersion, String> changes = null;
String display_url = null;
try {
if (mod.getUpdateURL().isEmpty())
return;
URL url = mod.getUpdateURL().get();
LOGGER.info("[{}] Starting version check at {}", mod.getModId(), url.toString());
String data = openUrlString(url);
LOGGER.debug("[{}] Received version check data:\n{}", mod.getModId(), data);
@SuppressWarnings("unchecked") Map<String, Object> json = new Gson().fromJson(data, Map.class);
@SuppressWarnings("unchecked") Map<String, String> promos = (Map<String, String>) json.get("promos");
display_url = (String) json.get("homepage");
var mcVersion = FMLLoader.versionInfo().mcVersion();
String rec = promos.get(mcVersion + "-recommended");
String lat = promos.get(mcVersion + "-latest");
ComparableVersion current = new ComparableVersion(mod.getVersion().toString());
if (rec != null) {
ComparableVersion recommended = new ComparableVersion(rec);
int diff = recommended.compareTo(current);
if (diff == 0)
status = UP_TO_DATE;
else if (diff < 0) {
status = AHEAD;
if (lat != null) {
ComparableVersion latest = new ComparableVersion(lat);
if (current.compareTo(latest) < 0) {
status = OUTDATED;
target = latest;
}
}
} else {
status = OUTDATED;
target = recommended;
}
} else if (lat != null) {
ComparableVersion latest = new ComparableVersion(lat);
if (current.compareTo(latest) < 0)
status = BETA_OUTDATED;
else
status = BETA;
target = latest;
} else
status = BETA;
LOGGER.info("[{}] Found status: {} Current: {} Target: {}", mod.getModId(), status, current, target);
changes = new LinkedHashMap<>();
@SuppressWarnings("unchecked") Map<String, String> tmp = (Map<String, String>) json.get(mcVersion);
if (tmp != null) {
List<ComparableVersion> ordered = new ArrayList<>();
for (String key : tmp.keySet()) {
ComparableVersion ver = new ComparableVersion(key);
if (ver.compareTo(current) > 0 && (target == null || ver.compareTo(target) < 1)) {
ordered.add(ver);
}
}
Collections.sort(ordered);
for (ComparableVersion ver : ordered) {
changes.put(ver, tmp.get(ver.toString()));
}
}
} catch (Exception e) {
LOGGER.warn("Failed to process update information", e);
status = FAILED;
}
results.put(mod, new CheckResult(status, target, changes, display_url));
}
}.start();
}
use of java.net.http.HttpClient in project redkale by redkale.
the class Utility method remoteHttpContentAsync.
public static CompletableFuture<ByteArrayOutputStream> remoteHttpContentAsync(java.net.http.HttpClient client, String method, String url, int timeout, Map<String, String> headers, String body) {
java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofMillis(timeout > 0 ? timeout : 6000)).method(method, body == null ? java.net.http.HttpRequest.BodyPublishers.noBody() : java.net.http.HttpRequest.BodyPublishers.ofString(body));
if (headers != null)
headers.forEach((n, v) -> builder.header(n, v));
java.net.http.HttpClient c = client == null ? httpClient : client;
if (c == null) {
synchronized (clientLock) {
if (httpClient == null) {
httpClient = java.net.http.HttpClient.newHttpClient();
}
}
c = httpClient;
}
return c.sendAsync(builder.build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray()).thenCompose((java.net.http.HttpResponse<byte[]> resp) -> {
final int rs = resp.statusCode();
if (rs == 301 || rs == 302) {
Optional<String> opt = resp.headers().firstValue("Location");
if (opt.isPresent()) {
return remoteHttpContentAsync(client, method, opt.get(), timeout, headers, body);
} else {
return CompletableFuture.failedFuture(new IOException(url + " httpcode = " + rs + ", but not found Localtion"));
}
}
byte[] result = resp.body();
if (rs == 200 || result != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (result != null) {
if ("gzip".equalsIgnoreCase(resp.headers().firstValue("content-encoding").orElse(null))) {
try {
GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(result));
in.transferTo(out);
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
}
} else {
out.writeBytes(result);
}
}
return CompletableFuture.completedFuture(out);
}
return CompletableFuture.failedFuture(new IOException(url + " httpcode = " + rs));
});
}
use of java.net.http.HttpClient in project feign by OpenFeign.
the class Http2Client method execute.
@Override
public Response execute(Request request, Options options) throws IOException {
final HttpRequest httpRequest;
try {
httpRequest = newRequestBuilder(request, options).version(client.version()).build();
} catch (URISyntaxException e) {
throw new IOException("Invalid uri " + request.url(), e);
}
HttpClient clientForRequest = getOrCreateClient(options);
HttpResponse<byte[]> httpResponse;
try {
httpResponse = clientForRequest.send(httpRequest, BodyHandlers.ofByteArray());
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Invalid uri " + request.url(), e);
}
return toFeignResponse(request, httpResponse);
}
Aggregations