Unirest 用法

Unirest 是一个轻量级的 HTTP 客户端库,支持多种编程语言,包括 Java、Node.js、Python 和其他一些语言。它简化了 HTTP 请求的发送过程,并且提供了易于使用的 API。

下面是几种不同编程语言中 Unirest 的基本用法示例:

1. Node.js (unirest 库)

首先,你需要安装 unirest 包:

npm install unirest

然后在你的 Node.js 项目中使用它:

const unirest = require('unirest');

// GET 请求
unirest.get('https://api.example.com/data')
  .headers({ 'accept': 'application/json' })
  .end((response) => {
    if (response.error) {
      console.log("Error:", response.error);
    } else {
      console.log("Response:", response.body);
    }
  });

// POST 请求
unirest.post('https://api.example.com/data')
  .headers({ 'content-type': 'application/json' })
  .send({ key: 'value' })
  .end((response) => {
    if (response.error) {
      console.log("Error:", response.error);
    } else {
      console.log("Response:", response.body);
    }
  });

2. Java (Unirest-java 库)

对于 Java,你需要添加 Maven 或 Gradle 依赖项:

Maven:

<dependency>
  <groupId>com.mashape.unirest</groupId>
  <artifactId>unirest-java</artifactId>
  <version>1.4.9</version>
</dependency>

Gradle:

implementation 'com.mashape.unirest:unirest-java:1.4.9'

使用 Unirest-java:

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class Main {
  public static void main(String[] args) {
    try {
      // GET 请求
      HttpResponse<JsonNode> jsonResponse = Unirest.get("https://api.example.com/data")
        .header("accept", "application/json")
        .asJson();
      
      System.out.println(jsonResponse.getBody());

      // POST 请求
      HttpResponse<JsonNode> postResponse = Unirest.post("https://api.example.com/data")
        .header("content-type", "application/json")
        .body("{\"key\": \"value\"}")
        .asJson();

      System.out.println(postResponse.getBody());
    } catch (UnirestException e) {
      e.printStackTrace();
    }
  }
}

3. Python (python-unirest 库)

对于 Python,你同样需要先安装库:

pip install python-unirest

然后使用它:

from unirest import get, post, delete

# GET 请求
response = get("https://api.example.com/data",
               headers={ "Accept": "application/json" })

print(response.body)

# POST 请求
response = post("https://api.example.com/data",
                headers={ "Content-Type": "application/json" },
                body="{\"key\": \"value\"}")

print(response.body)

这些示例展示了如何发送基本的 GET 和 POST 请求。Unirest 支持更多的请求类型和选项,你可以查看官方文档来获取更多信息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值