【问题标题】:Using 'POST' in PHP to retrieve database information via JSON in C#在 PHP 中使用“POST”通过 C# 中的 JSON 检索数据库信息
【发布时间】:2014-02-09 03:58:39
【问题描述】:

一整天都在搞砸我的大脑,我已经筋疲力尽了。我有一个 c# 跨平台移动应用程序。我需要从我的服务器上的 mysql 数据库中检索信息作为 JSON。无论我尝试什么(相信我,我已经用来自谷歌的许多方法重写了 php 和 c# 大约 20 次,但没有任何效果)。

我基本上需要 POST 一个 id,并通过 JSON 接收查询结果。

类似的东西:

PHP:

<?php
function getStatusCodeMessage($status)
{
$codes = parse_ini_file("codes.ini");

return (isset($codes[$status])) ? $codes[$status] : '';
}

function sendResponse($status = 200, $body = '', $content_type = 'application/json') 
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}

class myClass 
{

private $db;

function __construct() 
{
$this->db = new mysqli('localhost', 'user', 'pass', 'db');
$this->db->autocommit(FALSE);
}

function __destruct() 
{
$this->db->close();
}

function processRequest() 
{
if (isset($_POST["id"])) {
$id = $_POST["id"];

try {
$stmt = $this->db->prepare('SELECT 1, 2, 3, 4 FROM table WHERE id=?');
$stmt->bind_param("i", $id);
$result = $stmt->execute();
} catch(PDOException $ex) {
return false;
}

if($result){
$content = $stmt->fetchAll();
}

sendResponse(200, json_encode($content));
return true;
}

sendResponse(400, 'Invalid request');
return false;
}
}

$example = new myClass;
$example->processRequest();

?>

然后在 c# 中我需要类似的东西:

public string GetInfo(int id)
{
    string url = Globals.URL + "/GetInfo";
    string postData = "id=" + id;
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);


    WebRequest myRequest = WebRequest.Create(url);
    myRequest.Method = "POST";
    myRequest.ContentType = "application/json";
    myRequest.ContentLength = bytes.Length;

    try
    {
        Stream stream1 = myRequest.GetRequestStream();
        stream1.Write(bytes, 0, bytes.Length);
        stream1.Close();
        WebResponse response = myRequest.GetResponse();
        if (response == null)
            return null;
        StreamReader reader = new StreamReader(response.GetResponseStream());
        var result = reader.ReadToEnd();
    }
    catch (Exception)
    {
        output = "Something went wrong.";
    }

    if (result != null)
    {
        doSomethingWithJson(result);
        output = "Success!";
    }
    else
    {
        output = "Something went wrong.";
    }
    return output;
}

请记住,我只是在堆栈溢出邮箱中编写了这段代码,所以它并不完美。

我做错了什么?我如何获得 JSON 响应?目前我只能得到 400 错误请求或 500 服务器错误。

谢谢

编辑:

我发现这个问题是在使用 execute();而不是查询();。虽然执行适用于回声等,但您似乎无法使用它通过 httprequest 返回结果。我还发现 php 将 ID 转换为字符串,所以我不得不强制它使用 int。

类似的东西;

    if (isset($_POST["id"])) {
        $id = (int)$_POST["id"];

        $stmt = "SELECT 1,2,3,4 FROM table WHERE id = $id";

        try {
            foreach ($this->db->query($stmt) as $row) {
            $rows[] = $row;
            }
        } catch(PDOException $ex) {
            return false;
        }

        sendResponse(200, json_encode($rows));
        return true;
        }

如果您采用此解决方案,请记住不要“准备”SQL 语句,否则您将容易受到注入攻击,因此请务必对此采取措施;)

【问题讨论】:

  • 首先,您的 PHP 代码有效吗?您是否使用 POSTMAN 或其他类似工具对其进行了测试?专注于让服务器端工作,那么客户端代码应该很简单。
  • 不能通过邮递员工作。那么我该去哪里呢。
  • 这应该告诉您服务器端代码有问题。调试它。从方块 1 开始 - 您的数据库连接是否有效?你能做一个简单的选择吗?你能返回一个硬编码的 json 响应吗?验证每个部分,然后开始将它们组合在一起。

标签: c# php json mysqli xamarin


【解决方案1】:

我将展示使用 C# 执行此操作的方法 在您的网页中,假设您的网页表单中有名为 pageName.aspx 的按钮和文本框

<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<input type="button" value="Get" onclick="GetJSONData()" />

然后在body标签的底部添加脚本标签。还要正确添加 json 和 jquery 引用

<script src="../js/jquery.1.8.3.min.js" type="text/javascript"></script>
<script src="../js/json2.js" type="text/javascript"></script>
 <script type="text/javascript">
   function GetJSONData() {
       var id = $('#txtID').val();
       $.ajax({
           url: "pageName.aspx/GetData",   // Current Page, Method
           data: JSON.stringify({ id: id }), // parameter map as JSON  
           type: "POST", // data has to be POSTed  
           contentType: "application/json", // posting JSON content      
           dataType: "JSON",  // type of data is JSON (must be upper case!)  
           timeout: 10000,    // AJAX timeout  
           success: function(result) {
                   alert(result.d);
            },
            error: function(xhr, status) {
               alert(status + " - " + xhr.responseText);
           }
       });
   }

然后在后面的代码(pageName.aspx.cs)文件中添加以下方法。

[System.Web.Services.WebMethod]
    public static string GetData(string id)
    {
        string retData=string.Empty;
        //do whatever you want...
        //and assign result to retData
        return retData;
    }

【讨论】:

  • 很遗憾不能使用 asp.net,因为它是构建在一个在 linux 上运行的大型软件上的。不过很好的解决方案!
【解决方案2】:

您将返回 $result,这将是一个布尔值。见here。您要做的就是将$content 作为json 数组发送。

【讨论】:

  • 我的 Live Copy 有 $content,写这篇文章的时候把它塞进去了。
  • 你的c#代码中php文件的url对吗?尝试将该 url 直接放在浏览器中,并在您的 php 文件顶部添加 echo 以检查
  • 链接在 vis studio 中是正确的,但似乎 php 在 POSTMAN 中不起作用。
猜你喜欢
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
相关资源
最近更新 更多