Flutter-通过HTTP Post发送Json [英] Flutter - Send Json over HTTP Post

查看:635
本文介绍了Flutter-通过HTTP Post发送Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过HTTP发送Json来更新数据库中的记录.我已连接到服务器,但是在运行请求时出现415不受支持的媒体类型"错误.

I am trying to send a Json over HTTP post to update a record in my database. I've connected to the server but I'm getting a 415 "Unsupported Media Type" error when I run the request.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return new MaterialApp(
  home: new MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
String url = 'http://<Hostname>: 
<Port>/jderest/orchestrator/JDE_ORCH_Sample_UpdateMeterReadings_Generic';


Future<String> makeRequest() async {
var response = await http
    .post(Uri.encodeFull(url), body: json.encode({
  "NewHourMeterReading": "650",
  "EquipmentNumber": "34665",
  "NewFuelMeterReading": "650"
}), headers: {"Accept": "application/json"});

print(response.body);

}

@override
Widget build(BuildContext context) {
return new Scaffold(
    body: new Center(
        child: new RaisedButton(
          child: new Text('Make Request'),
          onPressed: makeRequest,
        )));
}
}

有人可以让我知道如何克服此错误吗?

Can someone please let me know how to get past this error?

我面临的错误是这个.

I/flutter(5881):不支持的媒体类型

I/flutter ( 5881): Unsupported Media Type

响应标题/状态代码/正文的屏幕截图

对不起,代码混乱,它没有在每个孔上复制粘贴.

Sorry for the messy code, it didn't copy paste over every well.

推荐答案

您必须将content-type添加到标题中,并将其值设置为application/json.

You'll have to add the content-type to your header, setting its value to application/json.

通过指定Accept,您是说您的客户能够理解该响应类型,而不是您的请求内容是JSON类型.

By specifying Accept you're saying that your client is able to understand that response type, not that your request content is of the JSON type.

基本上,您说的是嘿,我能够理解JSON,因此您可以将其发送给我,我会满意的",但您并不是在说嘿,我要发送您一个JSON,为此做好准备!"

Basically you're saying "hey there, I'm able to understand JSON, so you can send it to me and I'll be fine with it" but you're not saying "hey I'm going to send you a JSON, be prepared for it!"

为了更好地理解,您可以找到有关Accept的更多信息此处Content-type 此处.

For a better understanding, you can find more about Accept here and Content-type here.

这篇关于Flutter-通过HTTP Post发送Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆