首页 > 解决方案 > 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);
}

标签: c#phpjson

解决方案


推荐阅读