前言
curl可以用来访问http请求。
一、准备服务
CURLController.java
package com.student.controller;
import com.alibaba.fastjson.JSONObject;
import com.student.sys.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Create by zjg on 2023/4/28
*/
@RestController
public class CURLController {
public static final String CURL="curl";
@GetMapping(CURL)
public JSONObject get(@RequestHeader String token,@RequestParam(required = false) Integer pageSize,@RequestParam(required = false) Integer pageNumber){
System.out.println("token:"+token);
if(StringUtils.isEmpty(token)){
return error();
}
System.out.println(String.format("接收到请求参数pageSize:%s,pageNumber:%s",pageSize,pageNumber));
return success();
}
@PostMapping(CURL)
public JSONObject post(@RequestHeader String token,@RequestBody JSONObject jsonObject){
System.out.println("token:"+token);
if(StringUtils.isEmpty(token)){
return error();
}
System.out.println(String.format("接收到请求参数[jsonObject:%s]",jsonObject));
return success();
}
public JSONObject success(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg","操作成功");
jsonObject.put("code",200);
return jsonObject;
}
public JSONObject error(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg","处理失败");
jsonObject.put("code",1000);
return jsonObject;
}
}
二、curl
1.获取cookie
会在当前执行目录,生成cookie文件
curl -c "cookie" -d "username=admin&password=admin&rememberMe=true" http://localhost:8080/admin/login
2.get
curl -b "cookie" -H "token:token" "http://localhost:8080/curl?pageSize=1&pageNumber=10"
3.post
curl -b "cookie" -H "token:token" -H "Content-Type:application/json;charset=UTF-8" -d '{"pageSize": 1,"pageNumber": 10}' http://localhost:8080/curl
三、常用参数
参数 | 描述 |
---|---|
-c | 写入cookie文件 |
-d | data |
-b | 读取cookie文件 |
-H | 请求头 |
-X | 请求方式(GET,POST,PUT,DELETE) |
-i | 打印响应头 |
总结
-H为指定请求头,后面跟一个参数
回到顶部