Home > Net >  How to check the response from a POST request
How to check the response from a POST request

Time:10-29

How to check the value of "newOk":(true/false), which comes in the response body from the post request?

httpAddr = 'https://<link>'
client = WebClient()
client.Headers.Add("Content-Type","application/json")
client.Headers.Add("Authorization","Basic <code>")
client.Encoding = System.Text.Encoding.UTF8;
webRequest = WebRequest.Create(httpAddr);
reply = client.UploadString(httpAddr, body.ToString())

CodePudding user response:

To read the body of a response, you can use the method GetWebResponse (Read: https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.getwebresponse?view=net-6.0) on your WebClient object instance.

Then, in the WebReponse class you can use the method GetResponseStream to read the body of the response of that request.

Depending on how the body response is formatted (html, json, xml), you'll need to parse it with the appropriate .net class.

CodePudding user response:

I get it:

webRequest = WebRequest.Create(httpAddr);
try:
    reply = client.UploadString(httpAddr, body.ToString())
    if reply.ToString() == '{"newOk":true,"redirectOk":false,"rowCount":0,"datname":null}':
        log 'ID успешно изменен'
    if reply.ToString() == '{"newOk":false,"redirectOk":false,"rowCount":0,"datname":null}':
        log "Такой ID уже существует", 1  
        raise MacroError('Такой ID уже существует')

except e as System.Net.WebException:
    resp = StreamReader((e.Response as HttpWebResponse).GetResponseStream()).ReadToEnd()
    log "Произошла ошибка!"   e.Message.ToString(), 1
    log "Произошла ошибка!"   resp.ToString(), 1    
    raise MacroError("Произошла ошибка! Ошибка: ${e.Message}. Параметры запроса: body = ${body.ToString()}; httpAddr = ${httpAddr}; Ответ сервера = ${resp.ToString()}")
ensure:
    client.Dispose()
  • Related