java.net.http
modulemodule-info.java
module selflearn{
requires java.net.http;
}
var client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .connectTimeout(Duration.parse("PT3S")).build();
//Access Qiita to get content
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) {
try {
//HTTP client generation
var client = HttpClient.newHttpClient();
//Request preparation
var req = HttpRequest.newBuilder()
.uri(URI.create("https://qiita.com/"))
.build();
//Get response
var res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body());
//<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Qiita</title><meta content="Qiita is a technical information sharing service for programmers. Easily record programming tips, know-how, and notes&amp;You can publish it."(Abbreviation)
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
//Get response by asynchronous processing
client.send(req, HttpResponse.BodyHandlers.ofString())
.thenAccept(response -> {
System.out.println(response.body());
});
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
var client = HttpClient.newHttpClient();
//Receive name key and generate String
var req = HttpRequest.newBuilder()
.uri(URI.create("https://www.sample/post.php")) //"Hello,!"
.header("Content-Type","application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{ \"name\" : \"Qiita Neko\" }"))
.build();
var res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body()); //Hello, Qiita Neko-san!
}
}
post.php
<?php
$data = json_decode(file_get_contents('php://input'));
print ('Hello,'.$data->name.'San!');
Recommended Posts