下面列出了java.net.http.HttpRequest.BodyPublishers#java.net.http.HttpResponse.BodyHandlers 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void upload(String url, File file, String contentType) {
HttpRequest request;
try {
request = createRequest(url).header("Content-Type", contentType).PUT(BodyPublishers.ofFile(file.toPath())).build();
} catch (FileNotFoundException e) {
LOG.error("unable to upload: {}", url, e);
return;
}
httpclient.sendAsync(request, BodyHandlers.ofString()).exceptionally(ex -> {
Util.logIOException(LOG, "unable to upload: " + url, ex);
return null;
}).thenAccept(response -> {
if (response != null && response.statusCode() != 200 && LOG.isErrorEnabled()) {
LOG.error("unable to upload: {} response code: {}. response: {}", url, response.statusCode(), response.body());
}
});
}
/**
* Make the HTTP request without using the burp callbacks interface
*/
public void makeRequestWithoutBurp(){
HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(urlString))
.build();
try {
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
statusCode = (short) response.statusCode();
responseBody = response.body();
responseBodyBytes = response.body().getBytes();
}
catch (Exception ex) {
System.err.println("[-] There was an issue getting the JavaScript file at " + urlString);
ex.printStackTrace();
responseBody = NO_DATA_RECEIVED;
}
}
/**
* There is no reason that this should ever be called within burp. It is just here for tests.
* This uses incubated JDK libraries
*/
public void retrieveHtml(){
if (!url.equals("NONE")){
HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
try {
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
setHtml(response.body());
}
catch (Exception ex) {
System.err.println("[-] There was an issue getting the JavaScript file at " + url);
System.err.println(ex.toString());
ex.printStackTrace();
}
}
}
private SafeFuture<BLSSignature> sign(final Bytes signingRoot) {
final String publicKey = blsPublicKey.getPublicKey().toString();
return SafeFuture.ofComposed(
() -> {
final String requestBody = createSigningRequestBody(signingRoot);
final URI uri = signingServiceUrl.toURI().resolve("/signer/sign/" + publicKey);
final HttpRequest request =
HttpRequest.newBuilder()
.uri(uri)
.timeout(timeout)
.POST(BodyPublishers.ofString(requestBody))
.build();
return HttpClient.newHttpClient()
.sendAsync(request, BodyHandlers.ofString())
.handleAsync(this::getBlsSignature);
});
}
private static void get(){
HttpClient httpClient = HttpClient.newHttpClient();
/*
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2) // default
.build();
*/
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.GET() // default
.build();
try {
HttpResponse<String> resp = httpClient.send(req, BodyHandlers.ofString());
System.out.println("Response: " + resp.statusCode() + " : " + resp.body());
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void getAsync(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.GET() // default
.build();
/*
CompletableFuture<Void> cf =
httpClient.sendAsync(req, BodyHandlers.ofString())
.thenAccept(resp -> System.out.println("Response: " +
resp.statusCode() + " : " + resp.body()));
*/
CompletableFuture<String> cf =
httpClient.sendAsync(req, BodyHandlers.ofString())
.thenApply(resp -> "Server responded: " + resp.body());
System.out.println("The request was sent asynchronously...");
try {
System.out.println("CompletableFuture get: " +
cf.get(5, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the client...");
}
private static void postAsync(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.POST(BodyPublishers.ofString("Hi there!"))
.build();
CompletableFuture<String> cf =
httpClient.sendAsync(req, BodyHandlers.ofString())
.thenApply(resp -> "Server responded: " + resp.body());
System.out.println("The request was sent asynchronously...");
try {
System.out.println("CompletableFuture get: " +
cf.get(5, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the client...");
}
private static void push(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.GET()
.build();
CompletableFuture cf =
httpClient.sendAsync(req, BodyHandlers.ofString(), (PushPromiseHandler) HttpClientDemo::applyPushPromise);
System.out.println("The request was sent asynchronously...");
try {
System.out.println("CompletableFuture get: " + cf.get(5, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the client...");
}
@Override
public boolean contains(String password) throws IOException {
try {
var hash = hex(MessageDigest.getInstance("SHA1").digest(PasswordPolicy.normalize(password)));
var request =
HttpRequest.newBuilder()
.GET()
.uri(BASE_URI.resolve(hash.substring(0, PREFIX_LENGTH)))
.header("User-Agent", "passpol")
.build();
var response = client.send(request, BodyHandlers.ofLines());
if (response.statusCode() != 200) {
throw new IOException("Unexpected response from server: " + response.statusCode());
}
return response
.body()
.filter(s -> s.regionMatches(0, hash, PREFIX_LENGTH, SUFFIX_LENGTH))
.map(s -> s.substring(HASH_LENGTH + DELIM_LENGTH))
.mapToInt(Integer::parseInt)
.anyMatch(t -> t >= threshold);
} catch (NoSuchAlgorithmException | InterruptedException | IndexOutOfBoundsException e) {
throw new IOException(e);
}
}
@Override
public Integer call() throws Exception {
var serviceName = findServiceName();
var httpClient = HttpClient.newHttpClient();
var findVehicleRequest = HttpRequest.newBuilder()
.uri(buildRequestUri(serviceName))
.GET()
.build();
var response = httpClient.send(findVehicleRequest, BodyHandlers.ofByteArray());
var statusCode = response.statusCode();
if (statusCode == HTTP_OK) {
var vehicle = Vehicle.parseFrom(response.body());
System.out.println("Vehicle: " + vehicle);
return 0;
} else if (statusCode == HTTP_NOT_FOUND) {
System.out.printf("Vehicle with id (%s) is not found.%n", vehicleId);
return statusCode;
} else {
System.out.println("Status code: " + statusCode);
return statusCode;
}
}
/**
* Performs HTTP POST request.
* Credits https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java
* @param address the URL of the connection in String format, like "http://www.google.com"
* @param arguments the body of the POST request, as a HashMap
* @return response object
* @throws IOException if an I/O error occurs
* @throws InterruptedException if the operation is interrupted
*/
public static HttpResponse<String> httpPost(String address, HashMap<String, String> arguments)
throws IOException, InterruptedException {
var sj = new StringJoiner("&");
for (var entry : arguments.entrySet()) {
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
}
var out = sj.toString().getBytes(StandardCharsets.UTF_8);
var request = HttpRequest.newBuilder()
.uri(URI.create(address))
.headers("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.POST(BodyPublishers.ofByteArray(out))
.build();
return HttpClient.newHttpClient().send(request, BodyHandlers.ofString());
}
private static CompletableFuture<Void> reactiveSearch(HttpClient client, URI url, String term) {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(url)
.build();
StringFinder finder = new StringFinder(term);
client.sendAsync(request, BodyHandlers.fromLineSubscriber(finder))
.exceptionally(ex -> {
finder.onError(ex);
return null;
});
return finder
.found()
.exceptionally(Http2Api::handleError)
.thenAccept(found -> handleResult(url, found));
}
/**
* Sends the http request asynchronously to the API If the request is time out it creates a new
* response object with timeout set to true Otherwise it throws a run time exception
*
* @param request the request to send
* @throws AlgoliaRuntimeException When an error occurred processing the request on the server
* side
*/
public CompletableFuture<HttpResponse> performRequestAsync(@Nonnull HttpRequest request) {
return client
.sendAsync(buildRequest(request), BodyHandlers.ofInputStream())
.thenApply(this::buildResponse)
.exceptionally(
t -> {
if (t.getCause() instanceof HttpConnectTimeoutException
|| t.getCause() instanceof HttpTimeoutException) {
return new HttpResponse(true);
} else if (t.getCause() instanceof SecurityException
|| t.getCause() instanceof IOException
|| t.getCause() instanceof InterruptedException) {
return new HttpResponse().setNetworkError(true);
}
throw new AlgoliaRuntimeException(t);
});
}
public static void pushRequest() throws URISyntaxException, InterruptedException {
System.out.println("Running HTTP/2 Server Push example...");
HttpClient httpClient = HttpClient.newBuilder()
.version(Version.HTTP_2)
.build();
HttpRequest pageRequest = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush"))
.build();
// Interface HttpResponse.PushPromiseHandler<T>
// void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor)
httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
.thenAccept(pageResponse -> {
System.out.println("Page response status code: " + pageResponse.statusCode());
System.out.println("Page response headers: " + pageResponse.headers());
String responseBody = pageResponse.body();
System.out.println(responseBody);
}).join();
Thread.sleep(1000); // waiting for full response
}
@Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.proxy(ProxySelector.getDefault())
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample body"));
}
@Test
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.request()
.uri()
.toString(), equalTo("https://stackoverflow.com/"));
}
@Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth"))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
@Override
public Response execute(Request request, Options options) throws IOException {
final HttpRequest httpRequest = newRequestBuilder(request).build();
HttpResponse<byte[]> httpResponse;
try {
httpResponse = client.send(httpRequest, BodyHandlers.ofByteArray());
} catch (final InterruptedException e) {
throw new IOException("Invalid uri " + request.url(), e);
}
final OptionalLong length = httpResponse.headers().firstValueAsLong("Content-Length");
final Response response = Response.builder()
.body(new ByteArrayInputStream(httpResponse.body()),
length.isPresent() ? (int) length.getAsLong() : null)
.reason(httpResponse.headers().firstValue("Reason-Phrase").orElse("OK"))
.request(request)
.status(httpResponse.statusCode())
.headers(castMapCollectType(httpResponse.headers().map()))
.build();
return response;
}
private static void post(){
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3333/something"))
.POST(BodyPublishers.ofString("Hi there!"))
.build();
try {
HttpResponse<String> resp = httpClient.send(req, BodyHandlers.ofString());
System.out.println("Response: " + resp.statusCode() + " : " + resp.body());
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void applyPushPromise(HttpRequest initReq, HttpRequest pushReq,
Function<BodyHandler, CompletableFuture<HttpResponse>> acceptor) {
CompletableFuture<Void> cf = acceptor.apply(BodyHandlers.ofString())
.thenAccept(resp -> System.out.println("Got pushed response " + resp.uri()));
try {
System.out.println("Pushed completableFuture get: " + cf.get(1, TimeUnit.SECONDS));
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("Exit the applyPushPromise function...");
}
public void saveMetrics(JsonArray o) {
if (o == null || o.size() == 0) {
return;
}
HttpRequest request = createJsonRequest("/api/v1/metrics", o).build();
httpclient.sendAsync(request, BodyHandlers.ofString()).exceptionally(ex -> {
Util.logIOException(LOG, "unable to save metrics", ex);
return null;
}).thenAccept(response -> {
if (response != null && response.statusCode() != 200 && LOG.isErrorEnabled()) {
LOG.error("unable to save metrics. response code: {}. response: {}", response.statusCode(), response.body());
}
});
}
/**
* Performs HTTP GET request.
* @param uri the URI of the connection
* @return response object
* @throws Exception i/o error, interruption error, etc
*/
public static HttpResponse<String> httpGet(String uri) throws Exception {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.build();
return client.send(request, BodyHandlers.ofString());
}
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder().build();
HttpRequest post = HttpRequest
.newBuilder(POSTMAN_POST)
.POST(new LoggingBodyPublisher(BodyPublishers.ofFile(LARGE_JSON)))
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = client
.send(post, BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println(response.body());
}
private static boolean blockingSearch(HttpClient client, URI url, String term) {
try {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(url)
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
return response.body().contains(term);
} catch (IOException | InterruptedException ex) {
return handleError(ex);
}
}
private static CompletableFuture<Void> asyncSearch(HttpClient client, URI url, String term) {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(url)
.build();
return client
.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(body -> body.contains(term))
.exceptionally(Http2Api::handleError)
.thenAccept(found -> handleResult(url, found));
}
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException, InterruptedException {
// Create a GET sendHttpRequest to "http://example.com"
String url = "http://example.com";
var getRequest = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).GET().build();
// Send the sendHttpRequest using the client
var getResponse = client.send(getRequest, BodyHandlers.ofString());
// Write the results to the output:
var writer = new PrintWriter(response.getWriter());
writer.printf("Received code '%s' from url '%s'.", getResponse.statusCode(), url);
}
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
.headers("Accept-Enconding", "gzip, deflate")
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body();
int responseStatusCode = response.statusCode();
System.out.println("httpGetRequest: " + responseBody);
System.out.println("httpGetRequest status code: " + responseStatusCode);
}
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.version(HttpClient.Version.HTTP_2)
.POST(BodyPublishers.ofString("Sample Post Request"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body();
System.out.println("httpPostRequest : " + responseBody);
}