Получите InputStream и JSON в ответе RestTemplate с помощью postForObject

Поскольку вы используете C #, я думаю, вы должны использовать Windows API для подписки на определенные события Windows. Вы можете сделать это, используя класс EventLogWatcher или EventLog. Вы можете найти пример создания подписки на журнал событий Windows с помощью EventLog на MSDN .

Если вы предпочитаете EventLogWatcher, обратитесь к его ограниченной документации . И вот мой пример:

public static void subscribe()
{
    EventLogWatcher watcher = null;
    try
    {
        EventLogQuery subscriptionQuery = new EventLogQuery(
            "Security", PathType.LogName, "*[System/EventID=4624]");

        watcher = new EventLogWatcher(subscriptionQuery);

        // Make the watcher listen to the EventRecordWritten
        // events.  When this event happens, the callback method
        // (EventLogEventRead) is called.
        watcher.EventRecordWritten +=
            new EventHandler(
                EventLogEventRead);

        // Activate the subscription
        watcher.Enabled = true;

        for (int i = 0; i < 5; i++)
        {
            // Wait for events to occur. 
            System.Threading.Thread.Sleep(10000);
        }
    }
    catch (EventLogReadingException e)
    {
        Log("Error reading the log: {0}", e.Message);
    }
    finally
    {
        // Stop listening to events
        watcher.Enabled = false;

        if (watcher != null)
        {
            watcher.Dispose();
        }
    }
    Console.ReadKey();
}

// Callback method that gets executed when an event is
// reported to the subscription.
public static void EventLogEventRead(object obj,
    EventRecordWrittenEventArgs arg)
{
    // Make sure there was no error reading the event.
    if (arg.EventRecord != null)
    {
        //////
        // This section creates a list of XPath reference strings to select
        // the properties that we want to display
        // In this example, we will extract the User, TimeCreated, EventID and EventRecordID
        //////
        // Array of strings containing XPath references
        String[] xPathRefs = new String[9];
        xPathRefs[0] = "Event/System/TimeCreated/@SystemTime";
        xPathRefs[1] = "Event/System/Computer";
        xPathRefs[2] = "Event/EventData/Data[@Name=\"TargetUserName\"]";
        xPathRefs[3] = "Event/EventData/Data[@Name=\"TargetDomainName\"]";
        // Place those strings in an IEnumberable object
        IEnumerable xPathEnum = xPathRefs;
        // Create the property selection context using the XPath reference
        EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

        IList logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
        Log("Time: ", logEventProps[0]);
        Log("Computer: ", logEventProps[1]);
        Log("TargetUserName: ", logEventProps[2]);
        Log("TargetDomainName: ", logEventProps[3]);
        Log("---------------------------------------");

        Log("Description: ", arg.EventRecord.FormatDescription());
    }
    else
    {
        Log("The event instance was null.");
    }
}

2
задан Bhoomi 15 January 2019 в 21:41
поделиться

1 ответ

Когда дело доходит до работы с JSON и такими моделями, как в вашем примере «Тест», лучше всего использовать библиотеку, которая эффективно сериализует объекты в JSON. Я считаю, что Джексон, вероятно, одна из самых простых библиотек для использования с большим количеством ресурсов. Вы также можете использовать библиотеки Google Gson в качестве альтернативы.

Пример

pom.xml

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Service.class

HttpHeaders httpHeaders = < put headers here >
HttpEntity<EdpPartnerBean> entity = new HttpEntity<>(edpPartnerBean, httpHeaders);

// Will automatically use the Jackson serialization
ResponseEntity<Test> response = restTemplate.exchange(url, HttpMethod.POST, entity, Test.class);

Test.class

package x;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;


public class Test {

    private Boolean success;
    private String errorMessage;
    private String exceptionMessage;
    private String confirmation;
    private InputStream attachment;

    @JsonCreator
    public Test(@JsonProperty("success") Boolean success,
                @JsonProperty("errorMessage") String errorMessage,
                @JsonProperty("exceptionMessage") String exceptionMessage,
                @JsonProperty("confirmation") String confirmation,
                @JsonProperty("attachment") InputStream attachment) {
        this.setSuccess(success);
        this.setErrorMessage(errorMessage);
        this.setExceptionMessage(exceptionMessage);
        this.setConfirmation(confirmation);
        this.setAttachment(attachment);
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getExceptionMessage() {
        return exceptionMessage;
    }

    public void setExceptionMessage(String exceptionMessage) {
        this.exceptionMessage = exceptionMessage;
    }

    public String getConfirmation() {
        return confirmation;
    }

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public InputStream getAttachment() {
        return attachment;
    }

    public void setAttachment(InputStream attachment) {
        this.attachment = attachment;
    }
}

Обратите внимание на использование JsonCreator и JsonProperty.

Документация: https://github.com/FasterXML/jackson-docs

0
ответ дан Brandon 15 January 2019 в 21:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: