c# - WebClient.DownloadString:无效的 JSON 原语:
问题描述
我正在尝试使用 WebClient 从我的网络服务器上的 PHP 文件下载 JSON 字符串。
这是我的代码:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Web.Script.Serialization;
using System.Collections.Generic;
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static bool GetProgramInfo (string secret_key)
{
try
{
ServicePointManager.ServerCertificateValidationCallback += Methods.ValidateRemoteCertificate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(username, password);
client.Headers.Add(HttpRequestHeader.UserAgent, useragent);
string jsonData = client.DownloadString(url);
MessageBox.Show(jsonData);
}
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
}
我尝试删除所有与 JSON 相关的代码,包括 using 语句。程序恰好在 时进入中断模式string jsonData = client.DownloadString(url);
,我收到错误消息System.ArgumentException: 'Invalid JSON primitive: .'
。当我尝试使用.ToString()
.
PHP 脚本从 SQL 表返回数据,如下所示:
$stmt = $conn->prepare("SELECT id, value FROM `kl_general`");
$stmt->execute();
while ($row = $stmt->fetch()) {
if (intval($row['id'] == 5))
$version = $row['value'];
else if (intval($row['id']) == 6)
$hash = $row['value'];
}
$jsonFormat = json_encode(array('version' => $version, 'hash' => $hash));
die($jsonFormat);
当我直接访问服务器上的文件时,我得到缩进的结果:{"version":"3.0.0","hash":"a28fa7bab9878e42121efccb4e9277a8"}
更新
我尝试使用HttpClient
而不是WebClient
使用下面的代码,但产生了相同的错误:
using System.Net;
using System.Net.Http;
var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) }
using (var client = HttpClient(handler))
{
var result = client.GetStringAsync(url);
MessageBox.Show(result.Result);
}
解决方案
推荐阅读
- sql-server - 在 MS SSMS 中显示结果之前的消息
- django - 从只读字段中删除 Django admin 中的 help_text
- php - 从 WooCommerce 中的自定义字段更新 add_to_cart 上的用户元数据
- android - 如何获取位置的原始名称?
- angular - 如何在 Angular 6 中将第一个选项设置为默认值
- windows - 使 Windows 7/8/10 渲染到与屏幕不同的区域
- android - 重新激活时 Firemonkey TCameraComponent 质量发生变化
- java - 如何运行启动画面,然后是介绍滑块,然后是主要活动
- javascript - 如何在 SharePoint 上处理 JavaScript 预订系统的同时请求
- node.js - 猫鼬在哪里,我无法过滤数组