Как выбрать данные из базовой авторизации с почтовыми данными? - PullRequest
0 голосов
/ 20 ноября 2018

Как выбрать некоторые данные из этого сервиса (http://192.168.1.18/service/test), какое это значение> {"number": "11224455", "name": "person1"}. Базовая авторизация: {username: "admin",пароль: "pass123"}

Это пример выполнения запроса POST в C # с базовой аутентификацией: ошибка с: удаленный сервер возвратил ошибку: (401) не авторизован. где указан I имя пользователя и пароль?

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 ();
        }
    }
}

1 Ответ

0 голосов
/ 20 ноября 2018

Поскольку ваш комментарий, по-видимому, предполагает, что это единственный результирующий объект 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...