如何使用C#将JSon文件发送到远程Web服务器

时间:2018-05-17 05:44:23

标签: c# json httpwebrequest webrequest

我使用mysql和c#为Pharmacy管理系统创建了一个应用程序。他们也有本地和远程服务器上的数据库。基本上所有记录都存储在本地数据库中。然后应该使用JSon文件将新创建的记录上传到远程服务器。我还有使用php执行Json文件数据到远程服务器的代码。我使用json文件在桌面上有新记录。

JSon文件导出编码:

    private void btnExportToJson_Click(object sender, EventArgs e)
    {
        string contents = (DataTableToJSONWithStringBuilder(_dt));
        //MessageBox.Show(afd);
        System.IO.File.WriteAllText(@"C:\Users\NICK-PC\Desktop\path.json", contents);
        Application.Exit();
    }

JSon文件创建编码:

    public string DataTableToJSONWithStringBuilder(DataTable table)
    {
        var jsonString = new StringBuilder();
        if (table.Rows.Count > 0)
        {
            jsonString.Append("[\n");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                jsonString.Append("{\n");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
                                          table.Rows[i][j].ToString() + "\",\n");
                    }
                    else if (j == table.Columns.Count - 1)
                    {
                        jsonString.Append("\t\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" +
                                          table.Rows[i][j].ToString() + "\"");
                    }
                }

                if (i == table.Rows.Count - 1)
                {
                    jsonString.Append("}");
                }
                else
                {
                    jsonString.Append("\n},");
                    jsonString.Append("\n");
                }
            }

            jsonString.Append("\n]");
        }

        return jsonString.ToString();
    }

我使用了以下代码,但无效

public void jsonOps()
    {
        // Preparing Json object to send to the remote server
        jsonLogin li = new jsonLogin();
        li.username = "myadmin";
        li.password = "log@678*";
        string jLoginString = JsonConvert.SerializeObject(li);

        // Create HTTP POST request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.youraddress.com");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        httpWebRequest.Accept = "application/json";
        httpWebRequest.Method = "POST";

        string output = "";

        // Connecting to the server. Sending request and receiving response
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(jLoginString);
            streamWriter.Flush();
            streamWriter.Close();

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                output = streamReader.ReadToEnd();
            }
        }

        // Reading JSON response
        JsonTextReader reader = new JsonTextReader(new StringReader(output));
        while (reader.Read())
        {
            if (reader.Value != null)
            {
                textBox1.Text = reader.Value;
            }
            else
            {
                // No value exception block
            }
        }

1 个答案:

答案 0 :(得分:0)

我使用以下代码

    private void btnUploadToServer_Click(object sender, EventArgs e)
    {
        bool connection = NetworkInterface.GetIsNetworkAvailable();
        if (connection == true)
        {
            //MessageBox.Show("Internet Available");

            try
            {
                using (WebClient client = new WebClient())
                {
                    string filePath = @"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";
                    var myUri = new Uri(@"http://your_address/path/file.php");
                    client.UploadFile(myUri, filePath);
                    client.Credentials = CredentialCache.DefaultCredentials;
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

            MessageBox.Show("Successfully Uploaded", "Success");
            btnExecuteURL.Enabled = true;
        }

        else
        {
            MessageBox.Show("There is no internet connection.\n Please make sure that you have an internet connection.", "No Internet");
        }
    }