田源
2025-04-03 9b4433fddf5b401edb0aace8a404ac733b122702
Source/BladeX-Tool/blade-starter-http/src/test/java/org/springblade/core/http/test/HttpRequestDemo.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,130 @@
/*
 *      Copyright (c) 2018-2028, DreamLu All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: DreamLu å¢æ˜¥æ¢¦ (596392912@qq.com)
 */
package org.springblade.core.http.test;
import com.fasterxml.jackson.databind.JsonNode;
import org.springblade.core.http.HttpRequest;
import org.springblade.core.http.LogLevel;
import org.springblade.core.http.ResponseSpec;
import okhttp3.Cookie;
import org.springblade.core.tool.utils.Base64Util;
import java.net.URI;
import java.time.Duration;
import java.util.Optional;
/**
 * This example of blade http
 *
 * @author L.cm
 */
public class HttpRequestDemo {
   public void doc() {
      // è®¾å®šå…¨å±€æ—¥å¿—级别 NONE,BASIC,HEADERS,BODY, é»˜è®¤ï¼šNONE
      HttpRequest.setGlobalLog(LogLevel.BODY);
      // åŒæ­¥è¯·æ±‚ url,方法支持 get、post、patch、put、delete
      HttpRequest.get("https://www.baidu.com")
         .log(LogLevel.BASIC)             //设定本次的日志级别,优先于全局
         .addHeader("x-account-id", "blade001") // æ·»åŠ  header
         .addCookie(new Cookie.Builder()  // æ·»åŠ  cookie
            .name("sid")
            .value("blade_user_001")
            .build()
         )
         .query("q", "blade") //设置 url å‚数,默认进行 url encode
         .queryEncoded("name", "encodedValue")
         .formBuilder()    // è¡¨å•构造器,同类 multipartFormBuilder æ–‡ä»¶ä¸Šä¼ è¡¨å•
         .add("id", 123123) // è¡¨å•参数
         .execute()// å‘起请求
         .asJsonNode();
      // ç»“果集转换,注:如果网络异常等会直接抛出异常。
      // åŒç±»çš„æ–¹æ³•有 asString、asBytes
      // json ç±»å“åº”:asJsonNode、asObject、asList、asMap,采用 jackson å¤„理
      // xml、html响应:asDocument,采用的 jsoup å¤„理
      // file æ–‡ä»¶ï¼štoFile
      // åŒæ­¥
      String html = HttpRequest.post("https://www.baidu.com")
         .execute()
         .onSuccess(ResponseSpec::asString);// å¤„理响应,有网络异常等直接返回 null
      // åŒæ­¥
      String text = HttpRequest.patch("https://www.baidu.com")
         .execute()
         .onSuccess(ResponseSpec::asString);
      // onSuccess http code in [200..300) å¤„理响应,有网络异常等直接返回 null
      // å‘送异步请求
      HttpRequest.delete("https://www.baidu.com")
         .async() // å¼€å¯å¼‚æ­¥
         .onFailed((request, e) -> {    // å¼‚常时的处理
            e.printStackTrace();
         })
         .onSuccessful(responseSpec -> { // æ¶ˆè´¹å“åº”成功 http code in [200..300)
            // æ³¨æ„ï¼šå“åº”结果流只能读一次
            JsonNode jsonNode = responseSpec.asJsonNode();
         });
   }
   public static void main(String[] args) {
      // è®¾å®šå…¨å±€æ—¥å¿—级别
      HttpRequest.setGlobalLog(LogLevel.BODY);
      // åŒæ­¥ï¼Œå¼‚常时 è¿”回 null
      String html = HttpRequest.get("https://www.baidu.com")
         .connectTimeout(Duration.ofSeconds(1000))
         .query("test", "a")
         .query("name", "張三")
         .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);
      // åŒæ­¥è°ƒç”¨ï¼Œè¿”回 Optional,异常时返回 Optional.empty()
      Optional<String> opt = HttpRequest.post(URI.create("https://www.baidu.com"))
         .bodyString("Important stuff")
         .formBuilder()
         .add("a", "b")
         .execute()
         .onSuccessOpt(ResponseSpec::asString);
      // åŒæ­¥ï¼ŒæˆåŠŸæ—¶æ¶ˆè´¹ï¼ˆå¤„ç†ï¼‰ response
      HttpRequest.post("https://www.baidu.com/some-form")
         .addHeader("X-Custom-header", "stuff")
         .execute()
         .onFailed((request, e) -> {
            e.printStackTrace();
         })
         .onSuccessful(ResponseSpec::asString);
      // async,异步执行结果,失败时打印堆栈
      HttpRequest.get("https://www.baidu.com/some-form")
         .async()
         .onFailed((request, e) -> {
            e.printStackTrace();
         })
         .onSuccessful(System.out::println);
   }
}