如何使用C#将JSON文件发送至远程Web服务器(药房管理系统)
解决C#上传本地JSON文件到远程Web服务器的问题
看起来你的核心需求是把桌面上已经生成好的path.json文件内容发送到远程服务器,但你当前的代码是在发送一个登录对象的JSON,而不是本地文件的内容——这应该是代码未生效的主要原因之一。下面我们一步步来修正这个问题,同时用更可靠的方式实现上传。
先分析你现有代码的问题
- 你当前的代码序列化并发送的是
jsonLogin对象,而不是本地path.json文件里的实际内容 HttpWebRequest是较旧的API,写法繁琐且容易遗漏错误处理- 没有捕获可能的异常(比如网络连接失败、服务器返回错误码、文件读取失败等),很难排查问题
方案1:使用现代的HttpClient(推荐)
HttpClient是.NET中推荐的HTTP客户端,写法更简洁,也更容易维护。下面是读取本地JSON文件并发送到服务器的代码:
using System; using System.Net.Http; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; using System.Text; using System.Net.Http.Headers; // 建议放在异步方法中调用,比如按钮点击事件 private async void btnUploadJson_Click(object sender, EventArgs e) { // 本地JSON文件路径 string jsonFilePath = @"C:\Users\NICK-PC\Desktop\path.json"; // 检查文件是否存在 if (!File.Exists(jsonFilePath)) { MessageBox.Show("JSON文件不存在!"); return; } // 读取文件内容 string jsonContent = await File.ReadAllTextAsync(jsonFilePath); // 初始化HttpClient(注意:HttpClient应该全局复用,不要每次创建新实例) using (HttpClient client = new HttpClient()) { try { // 如果服务器需要登录验证,这里可以添加Basic Auth认证头 string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("myadmin:log@678*")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials); // 直接发送JSON文件内容 var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); // 发送POST请求到你的PHP服务器地址(替换为实际接口路径) HttpResponseMessage response = await client.PostAsync("https://www.youraddress.com/your-upload-endpoint.php", content); // 确保请求成功,若返回4xx/5xx状态码会抛出异常 response.EnsureSuccessStatusCode(); // 读取服务器响应 string responseContent = await response.Content.ReadAsStringAsync(); MessageBox.Show("上传成功!服务器响应:" + responseContent); textBox1.Text = responseContent; } catch (HttpRequestException ex) { MessageBox.Show("上传失败:" + ex.Message); } catch (Exception ex) { MessageBox.Show("发生错误:" + ex.Message); } } }
方案2:修正你的HttpWebRequest代码
如果你坚持使用HttpWebRequest,这里是修正后的版本,用来读取本地JSON文件并发送:
using System; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; public void UploadJsonFile() { string jsonFilePath = @"C:\Users\NICK-PC\Desktop\path.json"; if (!File.Exists(jsonFilePath)) { MessageBox.Show("JSON文件不存在!"); return; } string jsonContent = File.ReadAllText(jsonFilePath); string url = "https://www.youraddress.com/your-upload-endpoint.php"; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; httpWebRequest.Accept = "application/json"; httpWebRequest.Method = "POST"; // 添加Basic Auth登录验证 string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("myadmin:log@678*")); httpWebRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials; // 写入请求内容 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(jsonContent); streamWriter.Flush(); } // 获取响应 using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { string output = streamReader.ReadToEnd(); MessageBox.Show("上传成功!服务器响应:" + output); textBox1.Text = output; } } } catch (WebException ex) { // 处理Web异常,比如服务器返回4xx/5xx错误 if (ex.Response is HttpWebResponse errorResponse) { MessageBox.Show($"服务器错误:{(int)errorResponse.StatusCode} - {errorResponse.StatusDescription}"); } else { MessageBox.Show("上传失败:" + ex.Message); } } catch (Exception ex) { MessageBox.Show("发生错误:" + ex.Message); } }
关键注意事项
- 服务器端PHP处理:确保你的PHP代码正确接收POST请求的JSON内容,需要用
file_get_contents('php://input')读取请求体中的JSON数据(因为application/json类型的内容不会自动解析到$_POST数组里)。 - URL正确性:确认你请求的URL是正确的PHP接口地址,比如
https://www.youraddress.com/upload.php,而不是根域名。 - 权限问题:确保你的C#程序有读取桌面
path.json文件的权限,服务器端有写入/处理数据的权限。 - 异常处理:一定要添加异常捕获,这样能快速排查网络错误、服务器错误或文件读取错误。
- 认证方式:如果服务器需要登录验证,示例中用了Basic Auth,你也可以根据PHP端的要求调整为其他方式(比如Bearer Token)。
内容的提问来源于stack exchange,提问作者S.Sakthybaalan
相关产品推荐
相关产品推荐

