flutter 网络请求-Dio
get请求
1.get请求不带参数
[HttpGet] public string g1() { return "abc"; }
() async { try { Response response = await dio.get("https://127.0.0.1:5001/test/g1"); print(response.data); } catch (e) { print(e); } }();
2.get请求带参数
[HttpGet] public string g2(int a,string str) { return a.ToString()+str; }
Response response = await dio.get("https://127.0.0.1:5001/test/g2?a=3&str=abc");
或者
Response response = await dio.get("https://127.0.0.1:5001/test/g2",queryParameters: {"a":3,"str":"abc"});
或者
var data={'a':3,'str':'tom'}; () async { try { Response response = await dio.get("https://127.0.0.1:5001/test/g2",queryParameters:data); print(response.data); } catch (e) { print("打印:"+e.toString()); } }();
3.
[HttpGet] public string g3(Student student) { return student.name; }
传参数时,需要写在body里,get的body不推荐。
Post请求
1.post无参数
[HttpPost] public string p1() { return "abc"; }
Response response = await dio.post("https://127.0.0.1:5001/test/p1");
2.一个body参数
[HttpPost] public string p2([FromBody] string str) { return str; }
3.参数是一个类对象
[HttpPost] public string p3([FromBody] Student student) { return student.name; }
Response response = await dio.post("https://127.0.0.1:5001/test/p3",data: {"age":3,"name":"tom"});
4.参数是一个数组
[HttpPost] public string p4(string[] arr) { string str = ""; foreach (var a in arr) { str += a; } return str; }
List list=["a","b","c"]; Response response = await dio.post("https://127.0.0.1:5001/test/p4",data: list);
5. list对象集合
[HttpPost] public string p5(List<Student> list) { string str = ""; foreach (var stu in list) { str += stu.name; } return str; }
String str = '[{"age":18,"name":"tom"},{"age":22,"name":"liu"}]'; Response response = await dio.post("https://127.0.0.1:5001/test/p5", data: str);
6.传对象和参数混合
[HttpPost] public string p6(List<Student> list,string a,string b) { string str = ""; foreach (var stu in list) { str += stu.name; } return str+a+b; }
String str = '[{"age":18,"name":"tom"},{"age":22,"name":"liu"}]'; var str2={"a":"q","b":"w"}; Response response = await dio.post("https://127.0.0.1:5001/test/p6",queryParameters: str2, data: str);
7.表单
[HttpPost] public string p7([FromForm] Student student) { return student.name; }
FormData form=FormData.fromMap({"name": "tom", "age": 25,}); Response response = await dio.post("https://127.0.0.1:5001/test/p7",data:form);
访问https
Dio dio=Dio(); //使用https,忽略签名 (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) { client.badCertificateCallback=(X509Certificate cert, String host, int port){ return true; }; }; () async { try { Response response = await dio.get("https://127.0.0.1:5001/test/g1"); print(response); } catch (e) { print(e); } }();
加证书
String PEM="XXXXX"; // certificate content (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) { client.badCertificateCallback=(X509Certificate cert, String host, int port){ if(cert.pem==PEM){ // Verify the certificate return true; } return false; }; };