axios详解

什么使axios

axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js中发送HTTP请求。它可以在浏览器中使用XMLHttpRequest对象或者在Node.js中使用http模块发送请求。axios具有以下特点:
1. 支持Promise API:可以使用async/await或者.then/.catch来处理异步请求。
2. 支持拦截器:可以在请求或响应被发送或接收之前进行拦截和修改。
3. 支持取消请求:可以取消未完成的请求。
4. 支持CSRF防御:可以轻松地集成CSRF防御机制。
5. 支持浏览器和Node.js:可以在浏览器和Node.js环境中使用。

axios发送HTTP请求之发送GET和POST

发送GET请求

 

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    // 处理响应数据
    console.log(response.data);
  })
  .catch(error => {
    // 处理错误
    console.error(error);
  });

发送POST请求

import axios from 'axios';

const data = {
  name: 'John',
  age: 25
};

axios.post('https://api.example.com/user', data)
  .then(response => {
    // 处理响应数据
    console.log(response.data);
  })
  .catch(error => {
    // 处理错误
    console.error(error);
  });

用JAVASCRIPT发送GET请求

const url = "http://example.com/api";  // 请求的URL
const params = {param1: "value1", param2: "value2"};  // 请求参数

const queryString = new URLSearchParams(params).toString();  // 将参数转换为查询字符串

fetch(`${url}?${queryString}`)
  .then(response => {
    if (response.ok) {
      return response.json();  // 处理响应数据
    } else {
      throw new Error("请求失败");
    }
  })
  .then(data => {
    // 进行其他操作
  })
  .catch(error => {
    // 处理请求失败的情况
    console.error(error);
  });
  1. 使用Java的HttpURLConnection发送GET请求:

  2. import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Main {
        public static void main(String[] args) {
            String url = "http://example.com/api";  // 请求的URL
            String params = "param1=value1&param2=value2";  // 请求参数
    
            try {
                URL requestUrl = new URL(url + "?" + params);
                HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
                connection.setRequestMethod("GET");
    
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    StringBuilder response = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
    
                    // 处理响应数据
                    String responseData = response.toString();
                    // 进行其他操作
                } else {
                    // 处理请求失败的情况
                    System.out.println("请求失败");
                }
    
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    用JavaScript的FECRIPT函数发送POST请求

    const url = "http://example.com/api";  // 请求的URL
    const data = { key1: "value1", key2: "value2" };  // POST请求的数据
    
    fetch(url, {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));

    用JAVA的HttpURLConnection发送POST请求:

    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    
    public class PostRequestExample {
        public static void main(String[] args) throws Exception {
            String url = "http://example.com/api";  // 请求的URL
            String data = "key1=value1&key2=value2";  // POST请求的数据
    
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
    
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = data.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }
    
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
    
            // 读取响应内容
            // ...
        }
    }

    post请求JSON数据

    1. 使用请求头设置Content-Type为application/json,然后将JSON数据作为请求体发送。在大多数编程语言中,可以使用相应的库或框架来实现。例如,在Python中可以使用requests库,示例代码如下:
      import requests
      import json
      
      url = "http://example.com/api"
      data = {"key1": "value1", "key2": "value2"}
      headers = {"Content-Type": "application/json"}
      
      response = requests.post(url, data=json.dumps(data), headers=headers)
    2. 将JSON数据作为请求参数拼接在URL中发送。这种方式适用于简单的JSON数据,但不适合包含大量数据的情况。示例代码如下:
      import requests
      
      url = "http://example.com/api?key1=value1&key2=value2"
      
      response = requests.post(url)

  • 29
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值