jay jay
jay jay

Reputation: 25

Getting unexpected character error when I request using post method to the web service from Flutter application

What I am trying to do is to do post request to the URL but I am having an error saying *Format Exception: Unexpected Character". I am a beginner of Flutter application. Don't we need CSRF token? if the restful end point does not have CSRF token set, does the code works?

I tried most of the ways on Google but none of them works.

class _SendingInfoState extends State<SendingInfo> {
  String id;
  String description;
  double longitude;
  double latitude;
  Geolocator _geolocator;
  Position _position;

  @override
  void initState() {
    super.initState();
    id = widget.id;
    description = widget.desc;

    _geolocator = Geolocator();
    updateLocation();
    LocationOptions locationOptions =
        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 1);
    StreamSubscription positionStream = _geolocator
        .getPositionStream(locationOptions)
        .listen((Position position) {
      _position = position;
    });
  }

  void updateLocation() async {
    try {
      Position newPosition = await Geolocator()
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
          .timeout(new Duration(seconds: 5));
      longitude = _position.longitude;
      latitude = _position.latitude;
      setState(() {
        _position = newPosition;
      });
    } catch (e) {
      print('Error: ${e.toString()}');
    }
  }

  Future sendRequest(String id, String desc, double lat, double lon) async {
    print("id: " +
        id +
        "  Desc: " +
        desc +
        "  lat:  " +
        lat.toString() +
        "  lon: " +
        lon.toString());

    final sendData = await http.get(
      "http://developer.kensnz.com/api/addlocdata?userid=" +
          id +
          "&latitude=" +
          lat.toString() +
          "&longitude=" +
          lon.toString() +
          "&description=" +
          desc,
    );

    print(sendData.body);
  }

  Future<Map<String, dynamic>> sendRequestWithPost(
      String id, String desc, double lat, double lon) async {
    var client = http.Client();
    Map<String, dynamic> requestBody = {
      "userid": id,
      "latitude": lat,
      "longitude": lon,
      "description": desc
    };
    print("id: " +
        id +
        "  Desc: " +
        desc +
        "  lat:  " +
        lat.toString() +
        "  lon: " +
        lon.toString());
    String url = "post request URL!!!";

    final response = await client.post(
      Uri.encodeFull(url),
      body: """
      {
       "userid": $id,
      "latitude": $lat,
      "longitude": $lon,
      "description": $desc

      }

       """,
    ).whenComplete(client.close);

    if (!mounted) {
      return {'success': false};
    }
    setState(() {
      var res = json.decode(response.body);
      print(res);
    });
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.amber,
        title: Text("Location Sender"),
        actions: <Widget>[
          Padding(
            child: Icon(Icons.search),
            padding: const EdgeInsets.only(right: 10.0),
          )
        ],
      ),
      body: new Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(
                "ID: ${widget.id}",
                style: Theme.of(context).textTheme.title,
              ),
              new Text(
                "DESCRIPTION: ${widget.desc}",
                style: Theme.of(context).textTheme.title,
              ),
              new Text(
                "LATITUDE: ${_position != null ? _position.latitude.toString() : '0'}",
                style: Theme.of(context).textTheme.title,
              ),
              new Text(
                "LONGITUDE: ${_position != null ? _position.longitude.toString() : '0'}",
                style: Theme.of(context).textTheme.title,
              ),
              SizedBox(
                height: 150,
              ),
              new ListTile(
                title: new RaisedButton(
                  padding: EdgeInsets.all(25),
                  textTheme: ButtonTextTheme.primary,
                  color: Colors.amber,
                  child: new Text("POST LOCATION"),
                  onPressed: () {
                    sendRequestWithPost(id, description, latitude, longitude);
                  },
                ),
              ),
            ],
          ),
        ),
      ),
      //  new Text("${widget.id}"),
      // new Text("${widget.desc}"),
    );
  }
}

Error

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (17219): <!DOCTYPE html>
E/flutter (17219): ^
E/flutter (17219):
E/flutter (17219): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1392:5)
E/flutter (17219): #1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1259:9)
E/flutter (17219): #2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:924:22)
E/flutter (17219): #3      _parseJson (dart:convert-patch/convert_patch.dart:29:10)
E/flutter (17219): #4      JsonDecoder.convert (dart:convert/json.dart:493:36)
E/flutter (17219): #5      JsonCodec.decode (dart:convert/json.dart:151:41)
E/flutter (17219): #6      _SendingInfoState.sendRequestWithPost.<anonymous closure> (package:algorithm_send_location/pages/home_screen.dart:178:22)
E/flutter (17219): #7      State.setState (package:flutter/src/widgets/framework.dart:1141:30)
E/flutter (17219): #8      _SendingInfoState.sendRequestWithPost (package:algorithm_send_location/pages/home_screen.dart:177:5)
E/flutter (17219): <asynchronous suspension>
E/flutter (17219): #9      _SendingInfoState.build.<anonymous closure> (package:algorithm_send_location/pages/home_screen.dart:230:21)
E/flutter (17219): #10     _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:635:14)
E/flutter (17219): #11     _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:711:32)
E/flutter (17219): #12     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (17219): #13     TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365:11)
E/flutter (17219): #14     TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:275:7)
E/flutter (17219): #15     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:455:9)
E/flutter (17219): #16     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:75:13)
E/flutter (17219): #17     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:102:11)
E/flutter (17219): #18     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (17219): #19     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (17219): #20     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (17219): #21     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (17219): #22     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (17219): #23     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter (17219): #24     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (17219): #25     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (17219): #26     _invoke1 (dart:ui/hooks.dart:250:10)
E/flutter (17219): #27     _dispatchPointerDataPacket (dart:ui/hooks.dart:159:5)

Upvotes: 0

Views: 739

Answers (1)

Pablo Barrera
Pablo Barrera

Reputation: 10963

The response you are getting is HTML instead of JSON, that's why you have a FormatException

Upvotes: 2

Related Questions