flutter - Flutter - 如何在 Dart 中使用 HTTP 发送 POST 请求?
问题描述
我正在使用将 HTTP 转换为 JSON 并从服务器获得响应的 API,我需要发送 HTML 的发布请求,但是我不知道该怎么做?
这是我目前的实施 -
Future<String> test() async {
var link =
await http.get('https://example.com');
var body = parse(link.body);
return body.outerHtml;
}
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'text/html; charset=UTF-8',
},
body: html,
);
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
我称这是我的应用程序这样启动的时候,
@ovveride
void initState() {
test().then((body) => createAlbum(body)); //Output returns HTTP error 301, am I doing something wrong?
super.initState();
}
解决方案
检查了以下对我有用的代码。
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: html,
);
您需要将 Content-type 更改为application/x-www-form-urlencoded; charset=UTF-8
. 这应该可以解决问题。
推荐阅读
- swift - 无法将“NSTaggedPointerString”类型的值转换为“NSDictionary”
- asp.net - ASP.NET 中的 reactjs 与 razor 哪个更适合 seo?
- ios - 如何打开 .swiftmodule 文件
- java - 每个请求执行缓存
- python - Python:无法迭代模拟对象中的模拟数据库值
- android - 创建像选项菜单项一样的吐司点击并按住消息
- r - 按应用程序和用户 ID 分组后检索特定文本的所有行
- docker - docker run --net=host 是否类似于 AWS ECS 上的“主机”网络模式?
- python - 熊猫数据框中的值未排序
- reactjs - 无法将重新布局方法应用于图表,react-plotly.js