Research Problems Spring Boot reception parameters in the client sends a request to transfer data

Combined Cipian reference Spring Framework Study Notes (9) - API interface design specific knowledge and Coding

When using Spring Boot receive parameters, we found many problems before been busy recently little research available about this issue.

Most articles online, they talk about how Spring Boot achieve acceptable parameters, but not about how to call the client, Benpian use Jsoup, okhttp3 and postwoman testing tools shots, explain how to implement the interface on the server, while the client how to launch requests and parameter passing

Four kinds of requests presentation on

Web development may be just getting started you have doubts? Not only get and post these two?

In recent years it seems popular restful style interface, there are a variety of ways, according to the function to distinguish

However, currently we used only the following four ways get, post, put, delete

Essentially addition to get, others who are post way derived versions call when only need to modify the method name to (the specific code examples can be viewed in the way post)

get way

Introduction

Below, I wrote an interface

Because it is a local deployment, ip is localhost, contextpath called requestdemo, the default port 8080, so it is accessible urlhttp://localhost:8080/requestdemo/api/user/users

Since we are using @RequestMappingannotations, so, but what way have access to the data, as shown below, switch to post access

If you want to get a specified way, you can use @GetMappingannotations, GetMapping annotation is equivalent to such wording in fact @RequestMapping("users",method = [(RequestMethod.GET)]), received annotation method attribute is an array parameter

Get the specified manner using other post way, PUT, etc. are not return mode data, packet error code 405, as in FIG.

Receive data

@GetMapping("select")
fun selectByPk(@RequestParam("id") ids:Int):User {
    println(ids)
    return User("zhangsan",19)
}

@GetMapping("select1")
fun selectByPk1(ids:Int) {
    println(ids)
}

The first way should this client calls, you can enter the URL

http://localhost:8080/requestdemo/api/user/select?id=1

The second parameter is not annotated, so spring boot default to the variable name as a parameter, so it should be called with

http://localhost:8080/requestdemo/api/user/select1?ids=1

The following error screenshot also fully illustrates this point

Get request initiated by the client code

The client sends a written request to get the code is relatively simple, as long as we can put a good url splicing

Are p:

Jsoup get method is to return a Document (web object, after css can be screened to find the specified node, thereby obtaining content)

//需要ignoreContentType,忽略content-type,否则会报错,拿不到服务器返回的数据
val doc= Jsoup.connect("http://localhost:8080/requestdemo/api/user/select?id=1")
            .ignoreContentType(true)
            .get()
//输出服务器返回json数据         
println(doc.body().text())

Okhttp3:

val client = OkHttpClient()
val request = Request.Builder()
        .url("http://localhost:8080/requestdemo/api/user/select?id=1")
        .get()
        .build()
val call = client.newCall(request)
call.enqueue(object :Callback{
    override fun onFailure(call: Call, e: IOException) {

    }

    override fun onResponse(call: Call, response: Response) {
        println(response.body()?.string())
    }
})

post way

@RequestParam comment

@RequestParam for processing Content-Type: application of the content / x-www-form-urlencoded encoded submission GET, POST.

It has the following interfaces:

@PostMapping("update")
fun update(@RequestParam map: HashMap<String,String>) {
    //输出传入的key和value
    for (mutableEntry in map) {
        println(mutableEntry.key + "=" + mutableEntry.value)
    }
}

PS: can not RequestParam notes omitted, otherwise the back-end server does not receive data

Use postwoman test interface:

Note that the data format of form data in this way is application / x-www-form- urlencoded

Are p:

val dataMap = hashMapOf("name" to "zhangsag","age" to 11.toString())
val doc= Jsoup.connect("http://localhost:8080/requestdemo/api/user/update")
        .ignoreContentType(true)
        .data(dataMap)
        .post()
//输出结果      
 println(doc.body().text())     

The method of data may be acceptable Jsoup Map <String, String>, or key-value pair in the above example the following code can be changed

val doc= Jsoup.connect("http://localhost:8080/requestdemo/api/user/update")
            .ignoreContentType(true)
            .data("name","zhangsan")
            .data("age",12.toString())
            .post()
//输出结果          
 println(doc.body().text())         

Okhttp3:

fun sendPostRequest(){
    val url ="http://localhost:8080/requestdemo/api/user/update"
    val client = OkHttpClient()
    val formBodyBuilder = FormBody.Builder()
    formBodyBuilder.add("names", "zhangsxx")
    formBodyBuilder.add("ages", "19")
    val request = Request.Builder()
            .url(url)
            .post(formBodyBuilder.build())
            .build()
    val call = client.newCall(request)
    call.enqueue(object : Callback{
        override fun onFailure(call: Call, e: IOException) {

        }

        override fun onResponse(call: Call, response: Response) {
            
        }

    } )
}

There is a small problem not understood, if the interface is like the following, the client should be how to pass data? I tried several methods are given, said to be unable to type into User type String , is not this approach is not passed?

God wants to have a big passing can help answer

@PostMapping("update2")
fun update2(@RequestParam user: User) {
    println(user.toString())
}

@RequestBody comment

Sometimes, we need to pass a json string, we need to use this comment

It @RequestBody accept a string json object, not the object Json

We have one of the following interfaces:

@PostMapping("update1")
fun update1(@RequestBody user:User) {
    println(user.toString())
}

We pass the json data on the client side, after the spring boot will automatically call jackson framework, the json string data into entity classes

Are p:

val json = "{\"name\":\"zhangs\",\"age\":18}"
val doc= Jsoup.connect("http://localhost:8080/requestdemo/api/user/update1")
        .requestBody(json)
        .header("content-type","application/json")
        .post()

jsoup need to add up the request statement is transmitted json string data, by analogy, other forms of transfer only need to change the value of the content-type to other forms of

OkHttp3:

val json = "{\"name\":\"zhangs\",\"age\":18}"
val client = OkHttpClient()
val request = Request.Builder()
        .url("http://localhost:8080/requestdemo/api/user/update1")
        .post(RequestBody.create(MediaType.parse("application/json"),json))
        .build()
val call = client.newCall(request)
call.enqueue(object :Callback{
    override fun onFailure(call: Call, e: IOException) {

    }

    override fun onResponse(call: Call, response: Response) {
        println(response.body()?.string())
    }
})

Here somewhat similar to the above okhttp, the parameter data is not the same inside the post method

@RequestParam -> application/x-www-form-urlencoded -> FormBody

@RequestBody -> application/json -> RequestBody

By analogy, if it is xml format or binary format should be used to build RequestBody data, can operate on its own specific look, there is no longer demonstrates

How to put, delete way to write

Are p:

val json = "{\"name\":\"zhangs\",\"age\":18}"
val doc= Jsoup.connect("http://localhost:8080/requestdemo/api/user/update1")
        .requestBody(json)
        .header("content-type","application/json")
        .method(xx)
        .post()

Was added to the method in method, the figure is optional values:

Okhttp3, just take the post method to change or delete method can be put

val json = "{\"name\":\"zhangs\",\"age\":18}"
val client = OkHttpClient()
val request = Request.Builder()
        .url("http://localhost:8080/requestdemo/api/user/update1")
        //put或delete
        .put(RequestBody.create(MediaType.parse("application/json"),json))
        .build()
val call = client.newCall(request)
call.enqueue(object :Callback{
    override fun onFailure(call: Call, e: IOException) {

    }

    override fun onResponse(call: Call, response: Response) {
        println(response.body()?.string())
    }
})

ajax request code is transferred (added)

If ajax following codes:

var sg = 'UDZRb1loVWQFDAI9BTVcYFc6ADRTNQo8UWBQY1I5ASYBdVU_aXTEAYQdpBGEGagI2Vj4HO1Q7VmI_c';
$.ajax({
    type : 'post',
    url : '/ajaxm.php',
    data : { 'action':'downprocess','sign':sg,'ves':1 },
    dataType : 'json',
    success:function(msg){
        var date = msg;
        ...

Such requests should be in postwoman:

Jsoup Code:

//我这里不加头部,也可以获取到数据
val postUrl = "https://www.lanzous.com/ajaxm.php"
val params = LinkedHashMap<String, String>()
params["action"] = "downprocess"
params["sign"] = sign
params["ves"] = "1"

val result = Jsoup.connect(postUrl)
        .data(params)
        .post()
        .html()

reference

frombody POST
SpringBoot type appears the Content 'file application / X-WWW-form-urlencoded; charset = UTF-. 8' Not Supported
OKHTTP3 simple to use (c) the POST method

Guess you like

Origin www.cnblogs.com/stars-one/p/12506469.html