现在在我的Flutter应用程序上,我正在尝试做同样的事情:
运行该应用程序后...
{"error":true,"message":"Sorry, Auth key is not defined"}
我的代码是:
class Post {
String username;
Post({this.username});// call post API
factory Post.fromJson(Map<String, dynamic> json) {
return Post(username: json['username']);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["username"] = username;// post username
return map;
}
}
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
static final url = "http://xxxx.xxxxx.xxxx/xxxxx/login";// login API
TextEditingController _nameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Quiz App"),
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"User Name",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
color: Colors.blueAccent),
),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: _nameController,
maxLines: 1,
decoration: InputDecoration(
hintText: "User Name",
labelText: "Name",
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
borderSide: new BorderSide(
color: Colors.blueAccent,
width: 2.0,
),
),
),
),
),
Container(
width: 150,
height: 50,
child: FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0)),
color: Colors.blue,
onPressed: () async {
Future<Post> createPost(String url, {Map body}) async {
return http
.post(url, body: body, headers: {"auth_key": "xxxxxxxxx"})
.then((http.Response response) {
if (response.body.contains("xxx")) {
print("false value :" +response.body.toString());
} else if (response.body.contains("Success")) {
print("true value :" + response.body.toString());
//checkIsLogin();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen()));
} else {
print("else value :" + response.body.toString());
}
return Post.fromJson(json.decode(response.body));
});
}
Post newPost = new Post(username: _nameController.text);
Post p = await createPost(url, body: newPost.toMap());
print(p.username);
},
child: Text(
"SUBMIT",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.white,
letterSpacing: 1),
),
),
)
],
),
),
);
}
//save username with shared pref.
@override
void initState() {
super.initState();
checkIsLogin();
}
Future<Null> checkIsLogin() async {
String _auth_key = "";
//save key in shared pref
SharedPreferences prefs = await SharedPreferences.getInstance();
_auth_key = prefs.getString("auth_key");
if (_auth_key != "" && _auth_key != null) {
} else {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => SecondScreen()));
}
}
}
//this is secondscreen where call get api
class SecondScreen extends StatefulWidget {
@override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
static final url = "http://xxxx.xxxxx.xxxxxxx/xxxxxx/allCourse/";// course lisr API
List data;// save in list
@override
void initState() {
super.initState();
this.getJsonData();
}
Future<http.Request> getJsonData() async {
Response response = await http
.get(url, headers: {'Header': 'xxxxxxx'});
print(response.body);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson["course_list"];
});
}
//save data in list
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Courses"),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
child: Text(data[index]['xxxx']),
padding: EdgeInsets.all(20.0),
),
)
],
),
),
);
},
),
);
}
}`
我有用于提取列表的auth_key。
我在Postman中使用JSON请求标头测试了API,并且看起来工作正常。
这是响应...
{ "error": false, "message": "success", "course_list": [ { "courseId": "19", "courseName": "Verbs-01-def-prctice", "price": "0", "sub_type": "1", "sku_id": "15464", "courseIcon": "", "type": "0", "paid": false },
答案 0 :(得分:0)
尝试更改
Response response = await http.get(url, headers: {'Header': 'xxxxxxx'});
到
Response response = await http.get(Uri.encodeFull(url), headers:{"auth_key": "xxxxxxxxx"})
//the term "auth_key" used here should be the correct name the server
//is expecting for the authentication key. EDIT: In your Postman screen shot
// your have the key as "Header"
https://flutter.dev/docs/cookbook/networking/authenticated-requests