【问题标题】:flutter http post request returns html instead of jsonFlutter http post请求返回html而不是json
【发布时间】:2023-04-05 15:52:01
【问题描述】:

在我的颤振应用程序中,我决定通过从本地数据库 (xampp) 在线托管我的应用程序来上线,但现在每当我运行我的应用程序时,我都会不断获得

FormatException: Unexpected character (at character 1)
<html><body><script type="text/javascript" src="/aes.js" ></script><script>...

//Full html code
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("3bbe2c7d2bd575630c6e4c0b1537ed79");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="https://www.quelib.com/src/get_api/get_uni.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>

我在stackoverflow和谷歌上的其他网站上搜索过,但我得到的答案是添加标题

headers: {
  'Content-Type': 'application/json',
  'Charset': 'utf-8',
  "Accept": 'application/json'
}

或检查我的状态代码或使用 jsonEncode() 对我的正文参数进行编码,因为每当我使用 'Content-Type': 'application/json', 运行我的应用程序时,我都会收到 Bad State 错误

Future<List<String>> getAllUni() async {
    List<String> uniAll = [];
    try {
      var apiUrl = url + "get_api.php";
      final Map<String, dynamic> data = {"action": "GET_UNI"};
      await http.post(Uri.parse(apiUrl), body: jsonEncode(data), headers: {
        'Content-Type': 'application/json',
        'Charset': 'utf-8',
        "Accept": 'application/json'
      }).then((response) {
        debugPrint(response.body);
        debugPrint(json.decode(response.body));
        print(response.body);
        print(json.decode(response.body));
        if (json.decode(response.body) == 'no_data') {
        } else {
          List jDecode = json.decode(response.body);

          if (response.statusCode == 200) {
            jDecode.forEach((e) {
              print(e.toString());
              uniAll.add(e['name'].toString());
            });
          } else {}
        }
      });
    } catch (e) {
      ContentReport.report.catchReport("get_api.dart", "getAllUni",
          e.toString());
    }
    return uniAll;
}

我的 php 代码

$action = $_POST['action'];

if($action == 'GET_UNI') {

    $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
    $sql->execute();
    $res = $sql->get_result();
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res -> fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode($data);
    }
    else {
        echo json_encode("error_data");
    }
}

请问我该如何解决这个问题,因为 url 链接工作得很好。另外,如果您需要更多解释,请告诉我

【问题讨论】:

  • 你用邮递员试过了吗?

标签: php flutter dart http-headers http-post


【解决方案1】:
header('Content-type: application/json');
$action = $_POST['action'];

if($action == 'GET_UNI') {

    $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
    $sql->execute();
    $res = $sql->get_result();
    if (mysqli_num_rows($res) > 0) {
        while ($row = $res -> fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode($data);
    }
    else {
        echo json_encode("error_data");
    }
}

【讨论】:

  • header('Content-type: text/json');将此作为标题添加为您的 php 代码文件。
  • 你也可以使用 XMLHttpRequest.setRequestHeader(header, value) 在一个http请求中设置header。
  • 还是同样的错误
  • header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');也尝试使用它。
  • 还尝试从请求标头中删除 "Accept": 'application/json' 然后检查它是否已解决。
【解决方案2】:

使您的 PHP 代码响应信息更丰富。一旦使用如下代码:

<?php 
$response["error"] = false;
$response["errmsg"] = "No message";
$response["date"] = array();

if(isset($_POST["action"])){
    $action = $_POST['action'];
    if($action == 'GET_UNI') {

        $sql = $conn->prepare("SELECT * FROM uni ORDER BY name ASC");
        $sql->execute();
        $res = $sql->get_result();
        if (mysqli_num_rows($res) > 0) {
            while ($row = $res -> fetch_assoc()) {
                array_push($response["data"], $row);
            }
        }else {
            $response["error"] = true;
            $response["errmsg"] = "NO any row found.";
        }
    }
}else{
     $resposne["error"] = true;
     $response["errmsg"] = "No action parameter submitted through POST.";
}

header('Content-Type: application/json');
echo json_encode($response);
?>

您可以在 FlutterCampus 中查看此示例:Valid way to Generate Nested or Complex JSON data using PHP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多