Location>code7788 >text

HttpUtils

Popularity:117 ℃/2024-10-17 15:11:57

I. Detailed explanations

1.1 Introduction

In today's Web projects, the scenario of a server initiating a network request to the outside world is basically everywhere!
Traditionally, when accessing http services in server-side code, you generally use the JDK's HttpURLConnection or Apache's HttpClient, but this method is too cumbersome to use, and the api is very complex to use, and you have to worry about resource recovery.

1.2 What are HttpUtils?

  • HttpUtils is a client provided by Solon for making remote calls.
  • HttpUtils provides a lot of remote invocation methods , can greatly improve the efficiency of the client side of the writing . The HttpUtils interface implements HttpURLConnection adaptation (default), and OkHttp adaptation.
  • Official website address:solon-net-httputils

1.3 Introducing dependencies

<dependency>
    <groupId></groupId>
    <artifactId>solon-net-httputils</artifactId>
</dependency>

HttpUtils does not need to be initialized and can be used directly. Moreover, it is possible to use the load balancing capabilities directly (you need to introduce the solon-cloud plugin to provide the underlying support). Like this:

("user-service", "/user/get?id=1").get();

II. Interface use

HttpUtils biggest feature is the packaging of various network request methods, can greatly simplify the developer's workload, the following we GET, POST, PUT, DELETE, file uploads and downloads as an example, respectively, to introduce the use of various APIs.

2.1 GET requests

There are two frequently used methods for sending HTTP GET protocol requests via HttpUtils:

  • get() -> String
  • getAs(Type type) -> T (generalization support)

To write a unit test case in a Solon environment, first create an Api interface and then write unit tests to test the service.

Unparameterized get requests

@Controller
public class TestController {
    @Get
    @Mapping("testGet")
    public Result testGet(){
        Result result = new Result();
        ("200");
        ("demo...");
        return result;
    }
}

@Data
public class Result {
    private String code;
    private String msg;
}

Unit testing (get requests without parameters)

@Test
public void testGet(){
    //Request address
    String url = "http://localhost:8080/testGet";

    //Initiate the request, directly return the object
    Result result = (url).getAs().
    (());

Get requests with parameters (using placeholders)

@Controller
public class TestController {
    @Get
    @Mapping("testGetByRestFul/{id}/{name}")
    public Result testGetByRestFul(@Path("id") String id, @Path("name") String name){
        Result result = new Result();
        ("200");
        ("demo...");
        return result;
    }
}

Unit test (get request with parameters), with a header message added along the way.

@Test
public void testGetByRestFul(){
    //Request address
    String url = "http://localhost:8080/testGetByRestFul/001/John Doe";

    //Initiate the request, return the object directly (restful style)
    Result result = (url).header("App-Id", "1").getAs();
    (());
}

2.2 POST requests

In fact, the POST request method is similar to the GET request method, and the POST request in HttpUtils contains two main methods:

  • post() -> String
  • postAs(Type type) -> T(generalization support)

Simulate form request, post method test

@Controller
public class TestController {
    @Post
    @Mapping("testPostByForm")
    public Result testPostByForm(String userName, String userPwd){
        Result result = new Result();
        ("200");
        ("Demo...");
        return result;
    }
}

x-www-form-urlencoded post

@Test
public void testPostByForm(){
    //request address
    String url = "http://localhost:8080/testPostByForm";
 
    //initiate a request
    Result result = (url)
                             .data("userName", "Tripitaka (602-664) Tang dynasty Buddhist monk and translator, who traveled India 629-645")
                             .data("userPwd", "123456")
                             .postAs();
                  
    (());
}

form-data post, plus file upload by the way

@Test
public void testPostByForm(){
    //request address
    String url = "http://localhost:8080/testPostByForm";
 
    //initiate a request
    Result result = (url)
                             .data("userName", "Tripitaka (602-664) Tang dynasty Buddhist monk and translator, who traveled India 629-645")
                             .data("userPwd", "123456")
                             .data("file", "", new File("/data/"))
                             .postAs(, true); //useMultipart = true
                  
    (());
}

json-body post

@Test
public void testPostByForm(){
    //request address
    String url = "http://localhost:8080/testPostByForm";
 
    //initiate a request
    Result result = (url)
                             .bodyOfJson("{\"userName\":\"Tripitaka (602-664) Tang dynasty Buddhist monk and translator, who traveled India 629-645\",\"userPwd\":\"123456\"}")
                             .postAs();
                  
    (());
}

bean-body post

@Test
public void testPostByForm(){
    //request address
    String url = "http://localhost:8080/testPostByForm";
    
    UserBean user = new UserBean();
    ("Tripitaka (602-664) Tang dynasty Buddhist monk and translator, who traveled India 629-645");
    ("123456")
 
    //initiate a request
    Result result = (url)
                             .bodyOfBean(user)
                             .postAs();
                  
    (());
}

2.3 PUT, PATCH, DELETE requests

Usage is exactly the same as POST.

2.4 Advanced Usage

Getting a response (to close when you run out)

try(HttpResponse resp = ("http://localhost:8080/hello").data("name","world").exec("POST")) {
    int code = ();
    String head = ("Demo-Header");
    String body = ();
}

Configure the serializer. Defaults to json, change to fury; or define your own.

FuryBytesSerializer serializer = new FuryBytesSerializer();

Result body = ("http://localhost:8080/book")
                       .serializer(serializer)
                       .bodyOfBean(book)
                       .postAs();