curl请求接口

文章介绍了如何使用curl工具与Java编写的RESTController进行交互,包括通过curl获取cookie、执行GET和POST请求的方法,以及一些常用curl命令参数的总结,如请求头和数据的传递。
摘要由CSDN通过智能技术生成


前言

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文件
-ddata
-b读取cookie文件
-H请求头
-X请求方式(GET,POST,PUT,DELETE)
-i打印响应头

总结

-H为指定请求头,后面跟一个参数
回到顶部

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值