如何从此服务(http://192.168.1.18/service/test)中选择一些数据,该数据的值> {“数字”:“ 11224455”,“名称”:“ person1”} 。基本授权:{用户名:“ admin”,密码:“ pass123”}
这是使用基本身份验证在C#中发出POST请求的示例:出错,原因:远程服务器返回错误:(401)未经授权。用户名和密码放在哪里?
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main ()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://192.168.1.18/service/test");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}
答案 0 :(得分:1)
由于您的评论似乎暗示它是一个结果JSON对象:
使用需要捕获的属性声明您的课程:
public class Person
{
public int number { get; set; }
public string name { get; set; }
}
然后您可以通过类似以下内容的Newtonsoft.Json捕获它:
Person person = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(responseFromServer);
Console.WriteLine("id: {0}, name: {1}", person.name, person.number);