Guide to full use of mica-http [1]

Keywords: Java network JSON Spring OkHttp

mica-http

mica-http is an encapsulation of okhttp, an HTTP toolkit for Fluent syntax, and a syntax reference to the HttpClient Fluent API.

Use

maven

<dependency>
  <groupId>net.dreamlu</groupId>
  <artifactId>mica-http</artifactId>
  <version>${version}</version>
</dependency>

gradle

compile("net.dreamlu:mica-http:${version}")

Use Documentation

  • Set global log level NONE, BASIC, HEADERS, BODY, default: NONE
HttpRequest.setGlobalLog(LogLevel.BODY);
  • Synchronous request url, method supports get, post, patch, put, delete
HttpRequest.get("https://www.baidu.com")
    .log(LogLevel.BASIC)             //Set the log level this time, taking precedence over the global
    .addHeader("x-account-id", "mica001") // Add header
    .addCookie(new Cookie.Builder()  // Add cookie s
        .name("sid")
        .value("mica_user_001")
        .build()
    )
    .query("q", "mica") //Set url parameter, url encode by default
    .queryEncoded("name", "encodedValue")
    .formBuilder()    // Form builder, similar multipartFormBuilder file upload form
    .add("id", 123123) // Form parameters
    .execute()                      // Initiate Request
    .asJsonNode();                  // Result Set Conversion, Note: If a network exception, etc. throws an exception directly.
// The same methods are asString, asBytes, asStream
// json class response: asJsonNode, asValue, asList, asMap, with jackson processing
// xml, html response: jsoup processing used by asDocument, asDomValue, asDomList
// File file: toFile
  • synchronization
String html = HttpRequest.post("https://www.baidu.com")
    .execute()
    .onFailed((request, e) -> {// Consumption handling of abnormal situations such as network, etc.
        e.printStackTrace();
    })
    .onResponse(ResponseSpec::asString);// Handle responses, return null directly with network exceptions, etc.
  • synchronization
String text = HttpRequest.patch("https://www.baidu.com")
    .execute()
    .onSuccess(ResponseSpec::asString);
// OnSuccess HTTP code in [200..300] handles responses, returns null directly with network exceptions, etc.
  • Asynchronous request
HttpRequest.delete("https://www.baidu.com")
    .async() // Turn on asynchronous
    .onFailed((request, e) -> {    // Handling in case of exception
        e.printStackTrace();
    })
    .onResponse(responseSpec -> {  // Consumer response, note: the stream of response can only be read once
        int httpCode = responseSpec.code();

    })
    .onSuccessful(responseSpec -> { // Consumer response success HTTP code in [200..300]
        // Note: Response result stream can only be read once
        JsonNode jsonNode = responseSpec.asJsonNode();
    })
    .execute(); // Asynchronous Final Initiation Request

Sample Code 1

// Set Global Log Level
HttpRequest.setGlobalLog(LogLevel.BODY);

// Directly in jackson json path syntax
private String getUserEmail(String accessToken) {
    return HttpRequest.get("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))")
            .addHeader("Host", "api.linkedin.com")
            .addHeader("Connection", "Keep-Alive")
            .addHeader("Authorization", "Bearer " + accessToken)
            .execute()
            .asJsonNode()
            .at("/elements/0/handle~0/emailAddress")
            .asText();
}

// asynchronous
public static void test() {
    HttpRequest.post("https://www.baidu.com/do-stuff")
        .log(LogLevel.BASIC)                // log level
        .formBuilder()                      // Web Form Builder
        .add("a", "b")
        .async()                            // Use Asynchronous
        .onSuccessful(System.out::println)  // Functions on Asynchronous Success
        .onFailed((request, e) -> {         // Asynchronous failure, none
            e.printStackTrace();
        })
        .execute();
}

Sample Code 2

HttpRequest.setGlobalLog(LogLevel.BODY);

// Synchronize, return null on exception
String html = HttpRequest.get("www.baidu.com")
    .connectTimeout(Duration.ofSeconds(1000))
    .query("test", "a")
    .query("name", "Zhang San")
    .query("x", 1)
    .query("abd", Base64Util.encode("123&$#%"))
    .queryEncoded("abc", Base64Util.encode("123&$#%"))
    .execute()
    .onFailed(((request, e) -> {
        e.printStackTrace();
    }))
    .onSuccess(ResponseSpec::asString);
System.out.println(html);

// Synchronize calls, return Optional, and return Optional.empty() when an exception occurs
Optional<String> opt = HttpRequest.post(URI.create("https://www.baidu.com"))
    .bodyString("Important stuff")
    .formBuilder()
    .add("a", "b")
    .execute()
    .onSuccessOpt(ResponseSpec::asString);

// Synchronize, consume on success (process)
HttpRequest.post("https://www.baidu.com/some-form")
    .addHeader("X-Custom-header", "stuff")
    .execute()
    .onSuccessful(responseSpec -> {
        String text = responseSpec.asString();
        System.out.println(text);
    });

// Synchronization, thrown directly when an exception occurs
HttpRequest.get("https://www.baidu.com/some-form")
    .execute()
    .asString();

// async, asynchronous execution result, print stack on failure
HttpRequest.get("https://www.baidu.com/some-form")
    .async()
    .onSuccessful(System.out::println)
    .onFailed((request, e) -> {
        e.printStackTrace();
    })
    .execute();

File

Open source recommendation

Posted by BVis on Tue, 30 Jul 2019 10:00:53 -0700