【发布时间】: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