尝试发布以下代码:{grant_type: grant_type,密码: 123456,用户名: user1234}
Future<HttpClientResponse> apiRequest(String url, String username, String password) async {
Map jsonMap = {'grant_type':'password','password':password,'username':username};
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.add(utf8.encode((jsonMap.toString())));
print((jsonMap.toString()));
return await request.close();
}但是响应显示{“错误”:“invalid_request”,“error_description”:“缺少强制的'grant_type‘参数。”}。
在邮递员身上试着得到一个不同的结果
发布于 2020-02-07 18:20:46
我认为没有最好的办法。目前,我对Dart使用Retrofit,这非常方便,因为它生成了实际的实现。
例如,
@POST('/oauth/token')
@Headers(Constant.HEADER)
Future<LoginResponse> loginByEmail(@Query("email") String email,
@Query("password") String password, @Query("grant_type") String grantType);会变成
@override
loginByEmail(email, password, grantType) async {
ArgumentError.checkNotNull(email, 'email');
ArgumentError.checkNotNull(password, 'password');
ArgumentError.checkNotNull(grantType, 'grantType');
const _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{
'email': email,
'password': password,
'grant_type': grantType
};
final _data = <String, dynamic>{};
final Response<Map<String, dynamic>> _result = await _dio.request(
'/oauth/token',
queryParameters: queryParameters,
options: RequestOptions(
method: 'POST',
headers: <String, dynamic>{
},
extra: _extra,
baseUrl: baseUrl),
data: _data);
final value = LoginResponse.fromJson(_result.data);
return Future.value(value);
}发布于 2020-02-07 18:31:12
好的,我不知道您正在使用的方法,但是我将向您展示我的方法,它可以帮助您理解请求的结构。
服务器端代码显示:
POST - /api/getInfo
Request:
{
user_phone: ''
notes: ''
}
Response:
{
status: ''
}因此,这是服务器端的代码,这个请求( post请求)需要一个变量user_phone和一个变量注释。它给了我们地位的回应。
因此,我要对这个服务器发出一个请求的方法如下:
String basicAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password')); // <--- Generate the Basic Auth string
http.Response response = await http.get(
'https://myRandomServer.com/api/getInfo',
headers: <String, String>{'authorization': basicAuth}, // <--- Authorization in header
body: {'user_phone': '5555555555', 'notes': 'Some note'}, // <--- Data required in body of request
);
if (response.body != null) {
Map data = jsonDecode(responseStatus.body); // <--- Decoding from json file response
myStatus = data.['status']; // <---- Piece of information I need
}然而,现在有更多的方法可以帮助您了解原始代码可能出了什么问题,或者需要如何修改它来完成您想要做的事情。
https://stackoverflow.com/questions/60118765
复制相似问题