下面列出了java.net.http.HttpResponse.BodyHandlers#java.net.http.HttpResponse 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
/**
* creates an XmlItem
* this route creates an XmlItem
* @param xmlItem XmlItem Body (required)
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> createXmlItem(XmlItem xmlItem) throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = createXmlItemRequestBuilder(xmlItem);
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"createXmlItem call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* Logs out current logged in user session
*
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> logoutUser() throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = logoutUserRequestBuilder();
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"logoutUser call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2)
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertNotNull(response.body());
}
private List<Integer> querySubjectId(Integer pageNum) throws IOException, InterruptedException {
List<Integer> idList = new ArrayList<>(24);
int currentIndex = 0;
//开始查找id并添加到文件
for (; currentIndex < pageNum; currentIndex++) {
System.out.println("开始爬取第" + currentIndex + "页");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://bangumi.tv/anime/browser/?sort=date&page=" + currentIndex)).GET().build();
String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
//jsoup提取文本
Document doc = Jsoup.parse(body);
Elements elements = doc.getElementsByClass("subjectCover cover ll");
elements.forEach(e -> {
idList.add(Integer.parseInt(e.attr("href").replaceAll("\\D", "") + "\n"));
});
}
return idList;
}
/**
* Test processing.
*
* @throws Exception when an error occurs.
*/
@Test
public void testProcessing() throws Exception {
HttpServer server = createServer(8765);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 200);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
public void putUser() throws Exception {
UserVO userVO = new UserVO();
userVO.setId("3");
userVO.setName("X User 1");
userVO.setAddress("X Address 1");
userVO.setCity("X City 1");
userVO.setPhoneNo("1234567899");
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "/3"),
Optional.empty()
).PUT(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).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());
}
/**
* Test file.
*
* @throws Exception when a serious error occurs.
*/
@Test
public void testFile() throws Exception {
HttpServer server = createServer(8765);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/pom.xml")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
assertEquals(response.statusCode(), 200);
String responseText = response.body();
assertTrue(responseText.contains("modelVersion"));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
private void pullACG17News() throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://acg17.com/category/news/")).GET().build();
String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
Document doc = Jsoup.parse(body);
Elements elements = doc.getElementsByClass("item-list");
List<ACGNew> acgNewList = elements.stream().map(e -> {
String style = e.getElementsByClass("attachment-tie-medium size-tie-medium wp-post-image").get(0).attr("style");
String cover = style.substring(style.indexOf("url(") + 4, style.indexOf(")"));
Element t = e.getElementsByClass("post-box-title").get(0).child(0);
LocalDate createDate = LocalDate.parse(e.getElementsByClass("tie-date").get(0).text().replaceAll("[年月]", "-").replace("日", ""));
String intro = e.getElementsByClass("entry").get(0).child(0).text();
String title = t.text();
String rerfererUrl = t.attr("href");
return new ACGNew(title, intro, NewsCrawlerConstant.ACG17, cover, rerfererUrl, createDate, NewsCrawlerConstant.ACG17);
}).collect(Collectors.toList());
process(acgNewList, "class", "entry");
}
public CompletableFuture<String> getJson(String url) {
HttpRequest.Builder uri = HttpRequest.newBuilder()
.uri(URI.create(url));
decorateHeader(uri);
PixivUser pixivUser = oauthManager.getRandomPixivUser();
HttpRequest getRank = uri
.header("Authorization", "Bearer " + pixivUser.getAccessToken())
.GET()
.build();
return httpClient.sendAsync(getRank, HttpResponse.BodyHandlers.ofString()).thenApply(resp -> {
int code = resp.statusCode();
//System.out.println(resp.body().length());
if (code == 403) {
pixivUser.ban();
return "false";
}
return resp.body();
});
}
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 static void main(String[] args) throws IOException, InterruptedException {
System.out.println("Downloading (please wait) ...");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://demo.borland.com/testsite/downloads/downloadfile.php?file=Hello.txt&cd=attachment+filename"))
.build();
HttpResponse<Path> response = client.send(
request, HttpResponse.BodyHandlers
.ofFileDownload(Path.of(System.getProperty("user.dir")), CREATE, WRITE));
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
}
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
.thenApply(HttpResponse::body)
.thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
.join();
System.out.println("\nPush promises map size: " + promisesMap.size() + "\n");
promisesMap.entrySet().forEach((entry) -> {
System.out.println("Request = " + entry.getKey()
+ ", \nResponse = " + entry.getValue().join().body());
});
}
private void pullFUTA404News() throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://www.futa404.com/category/dmaz")).GET().build();
String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
Document doc = Jsoup.parse(body);
Elements elements = doc.getElementsByClass("card flex-fill mb-4 mb-sm-4-2 mb-md-4 mb-lg-4-2");
List<ACGNew> acgNewList = elements.stream().map(e -> {
String cover = e.getElementsByClass("lazyload custom-hover-img original").get(0).attr("src");
Element t = e.getElementsByClass("custom-hover d-block").get(0);
String title = t.attr("title");
String rerfererUrl = t.attr("href");
String time = e.getElementsByClass("u-time").get(0).text();
LocalDate createDate;
if (time.contains("-")) {
createDate = LocalDate.parse(time);
} else {
createDate = LocalDate.now();
}
String intro = e.getElementsByClass("text-l2 font-md-12 text-secondary").get(0).text();
return new ACGNew(title, intro, NewsCrawlerConstant.FUTA404, cover, rerfererUrl, createDate, NewsCrawlerConstant.FUTA404);
}).collect(Collectors.toList());
process(acgNewList, "class", "post-content suxing-popup-gallery");
}
@Test
void responses_HaveProperInputStream() throws IOException, InterruptedException {
service.get("/input-stream", context -> {
context.response().result(inputStream("cv.pdf"));
});
service.ignite();
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3030/input-stream"))
.GET()
.build();
final var send = httpClient.send(request, HttpResponse
.BodyHandlers.ofInputStream());
assertThat(IOUtils.contentEquals(inputStream("cv.pdf"), send.body()))
.isTrue();
}
/**
*
* For this test, the body for this request much reference a schema named `File`.
* @param body (required)
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> testBodyWithFileSchema(FileSchemaTestClass body) throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = testBodyWithFileSchemaRequestBuilder(body);
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"testBodyWithFileSchema call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* Test processing.
*
* @throws Exception when an error occurs.
*/
@Test
public void testProcessing2() throws Exception {
HttpServer server = createServer(8765);
server.start();
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(response.statusCode(), 200);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
server.stop();
}
}
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param number None (required)
* @param _double None (required)
* @param patternWithoutDelimiter None (required)
* @param _byte None (required)
* @param integer None (optional)
* @param int32 None (optional)
* @param int64 None (optional)
* @param _float None (optional)
* @param string None (optional)
* @param binary None (optional)
* @param date None (optional)
* @param dateTime None (optional)
* @param password None (optional)
* @param paramCallback None (optional)
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = testEndpointParametersRequestBuilder(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"testEndpointParameters call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* 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;
}
}
@Test
public void helloHttp_shouldRunWithFunctionsFramework() throws Throwable {
String functionUrl = BASE_URL + "/helloHttp";
HttpRequest getRequest = HttpRequest.newBuilder().uri(URI.create(functionUrl)).GET().build();
// The Functions Framework Maven plugin process takes time to start up
// Use resilience4j to retry the test HTTP request until the plugin responds
RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
.maxAttempts(8)
.intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
.retryExceptions(IOException.class)
.build());
Retry retry = registry.retry("my");
// Perform the request-retry process
String body = Retry.decorateCheckedSupplier(retry, () -> client.send(
getRequest,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body()
).apply();
// Verify the function returned the right results
assertThat(body).isEqualTo("Hello world!");
}
@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 postJson() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
Book book = new Book(1, "Java HttpClient in practice");
String body = objectMapper.writeValueAsString(book);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/test/resource"))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(200);
assertThat(objectMapper.readValue(response.body(), Book.class).id).isEqualTo(1);
}
@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));
}
/**
*
* To test the collection format in query parameters
* @param pipe (required)
* @param ioutil (required)
* @param http (required)
* @param url (required)
* @param context (required)
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> testQueryParameterCollectionFormat(List<String> pipe, List<String> ioutil, List<String> http, List<String> url, List<String> context) throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = testQueryParameterCollectionFormatRequestBuilder(pipe, ioutil, http, url, context);
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"testQueryParameterCollectionFormat call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object (required)
* @throws ApiException if fails to make API call
*/
public CompletableFuture<Void> createUser(User body) throws ApiException {
try {
HttpRequest.Builder localVarRequestBuilder = createUserRequestBuilder(body);
return memberVarHttpClient.sendAsync(
localVarRequestBuilder.build(),
HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
if (localVarResponse.statusCode()/ 100 != 2) {
return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
"createUser call received non-success response",
localVarResponse.headers(),
localVarResponse.body())
);
} else {
return CompletableFuture.completedFuture(null);
}
});
}
catch (ApiException e) {
return CompletableFuture.failedFuture(e);
}
}
private R sendRequest(ChannelDeserializer<R> deser, HttpRequest request) throws java.io.IOException, InterruptedException {
if (requestCustomizer != null)
requestCustomizer.accept(request);
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (deser == null)
return null;
if (encodeBase64)
return deser.deserialize(Base64.getDecoder().decode(response.body()));
else
return deser.deserializeString(response.body());
}
@Test
public void helloHttp_shouldRunWithFunctionsFramework() throws IOException, InterruptedException {
String functionUrl = BASE_URL + "/HelloHttp";
java.net.http.HttpRequest getRequest =
java.net.http.HttpRequest.newBuilder().uri(URI.create(functionUrl)).GET().build();
HttpResponse response = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
assertThat(response.body().toString()).isEqualTo("Hello world!");
}
@Test
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.timeout(Duration.of(10, SECONDS))
.GET()
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
@Cacheable(value = "searchSuggestions")
public CompletableFuture<List<SearchSuggestion>> getSearchSuggestionFromMoeGirl(@SensitiveCheck String keyword) {
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://zh.moegirl.org/index.php?limit=2&search=" + URLEncoder.encode(keyword, StandardCharsets.UTF_8)))
.build();
//正则提取关键词
return httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()).thenApply(r ->
moeGirlPattern.matcher(r.body()).results().map(result -> {
String matchKeyword = result.group();
return new SearchSuggestion(matchKeyword, translatedByYouDao(keyword));
}).collect(Collectors.toList())
);
}
/**
* Test the Piranha Micro command line.
*
* @throws Exception when a serious error occurs.
*/
@Test
@Disabled
public void testCommandLine() throws Exception {
String version = System.getProperty("VERSION");
ProcessBuilder builder = new ProcessBuilder();
builder.command("java", "-jar", "target/piranha-micro-" + version + "-all.jar");
Process process = builder.start();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8080/")).build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertEquals(response.statusCode(), 404);
process.destroyForcibly();
}