Flutter发送HTTP请求

文章详细描述了一个JavaSpringMVC服务器端的UserController,用于处理GET和POST请求,以及Flutter客户端如何通过http包进行HTTP请求的示例。
摘要由CSDN通过智能技术生成

Java服务器端(Server)

package com.example.signserver.controller;


import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping(value = "/base")
public class UserController {
    @GetMapping(value = "/getUser", produces = MediaType.APPLICATION_JSON_VALUE + "; charset=UTF-8")
    public ResponseEntity test(){
        User1 user1 = new User1();
        user1.setFirstName("张三");
        user1.setLastName("李四");
        return ResponseEntity.ok(Map.of("code",200,"data",user1));
    }
    @PostMapping(value = "/setUser", produces = MediaType.APPLICATION_JSON_VALUE + "; charset=UTF-8")
    public ResponseEntity testSet(@RequestBody User1 user) {
        return ResponseEntity.ok(Map.of("code",200,"data",user));
    }
}
@Data
class User1{
    @JsonProperty("first_name")
    private String firstName;
    @JsonProperty("last_name")
    private String lastName;
}

Flutter客户端(Client)

首先在 pubspec.yaml 文件中添加 http 包的依赖,然后运行 flutter pub get 命令来安装该包。最后在 Dart 文件中使用 import 关键字来导入 http 包使用即可。

1、添加依赖

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

2、安装依赖包

运行 flutter pub get 命令来安装该包

flutter pub get

3、编写工具类(附使用示例)

import 'dart:convert';
import 'package:http/http.dart' as http;

class HttpUtils {
  static Future<Map<String, dynamic>> request(
    String url, {
      Map<String, String>? headers,
      Map<String, dynamic>? params,
      dynamic body,
      String method = 'GET',
      String contentType = 'application/json; charset=utf-8',
    }) async {
    http.Response response;
    if (method.toUpperCase() == 'GET') {
      if (params != null && params.isNotEmpty) {
        String queryString = Uri(queryParameters: params).query;
        url += '?' + queryString;
      }
      response = await http.get(Uri.parse(url), headers: headers);
    } else {
      Map<String, String> _headers = {
        'Content-Type': contentType,
        if (headers != null) ...headers,
      };
      response = await http.post(Uri.parse(url), headers: _headers, body: body);
    }

    Map<String, dynamic> result = {
      'statusCode': response.statusCode,
      'headers': response.headers,
    };

    if (response.statusCode == 200) {
      result['data'] = json.decode(response.body);
    } else {
      result['data'] = null;
    }

    return result;
  }
}

//使用示例
void main() async {
  // GET 请求示例
  Map<String, dynamic> response1 = await HttpUtils.request(
    'http://localhost:8081/base/getUser',
    method: 'GET',
  );
  // GET 请求结果:{code: 200, data: {first_name: 张三, last_name: 李四}}
  print('GET 请求结果:${response1['data']}');
  // GET 请求结果:张三
  print('GET 请求结果:${response1['data']['data']['first_name']}');

  // POST 请求示例
  Map<String, dynamic> response2 = await HttpUtils.request(
    'http://localhost:8081/base/setUser',
    method: 'POST',
    contentType: 'application/json; charset=utf-8',
    body: json.encode({'first_name': '张三', 'last_name': '李四'}),
  );
  // POST 请求结果:{data: {first_name: 张三, last_name: 李四}, code: 200}
  print('POST 请求结果:${response2['data']}');
}

运行main打印结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值