Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Send Json over HTTP Post

Tags:

flutter

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?

the error that I am facing is this.

I/flutter ( 5881): Unsupported Media Type

Screenshot of Response Headers/Status Code/Body

enter image description here

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

like image 566
Flynn Avatar asked Nov 20 '18 07:11

Flynn


People also ask

How do you get a post response on Flutter?

If you want to send an HTTP Post request in Flutter or Dart, you can use the code examples explained in this post. We are using package 'package:http/http. dart' to send a post request in Flutter. We are also sending data in our post request and getting the response in the response named variable.


1 Answers

You are using incomplete headers for sending the json payload. That is why the server is not accepting you request.

Use the following headers instead:

headers: {
        "content-type" : "application/json",
        "accept" : "application/json",
      },
like image 52
Harsh Bhikadia Avatar answered Sep 18 '22 06:09

Harsh Bhikadia