[Java] Content acquisition with HttpCliient

Get content via HTTP

module-info.java


module selflearn{
  requires java.net.http;
}
//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;amp;You can publish it."(Abbreviation)
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }
  }
}

Asynchronous request transmission

//Get response by asynchronous processing
client.send(req, HttpResponse.BodyHandlers.ofString())
.thenAccept(response -> {
  System.out.println(response.body());
});

HTTP POST data communication

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

[Java] Content acquisition with HttpCliient
[Java] JSON communication with jackson
[Java] Content acquisition with HttpCliient
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Endian conversion with JAVA
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java basic learning content 7 (exception)
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java to play with Function
Try DB connection with Java
Java basic learning content 5 (modifier)
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
Java version control with jenv
Troubleshooting with Java Flight Recorder
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate
Getting Started with Java Basics
Seasonal display with Java switch
Use SpatiaLite with Java / JDBC
Study Java with Progate Note 1
Compare Java 8 Optional with Swift
HTML parsing with JAVA (scraping)
Java Basic Learning Content 8 (Java API)
Run Java VM with WebAssembly
Java basic learning content 4 (repetition)
Screen transition with swing, java
Java unit tests with Mockito
[Java 8] Duplicate deletion (& duplicate check) with Stream
Create an immutable class with JAVA
Java lambda expressions learned with Comparator
[Java, Scala] Image resizing with ImageIO
Build a Java project with Gradle
Install java with Ubuntu 16.04 based Docker
Morphological analysis in Java with Kuromoji
Use java with MSYS and Cygwin
100% Pure Java BDD with JGiven (Introduction)