Postman и HttpWebRequest дают разные результаты

#c# #httprequest #httpresponse #system.net.httpwebrequest

#c# #httprequest #httpresponse #system.net.httpwebrequest

Вопрос:

Я новичок в C #, и я хочу отправить запрос в формате JSON в API и получить ответ JSON в ответ, чтобы я мог использовать его в своем приложении. Но каждый раз, когда я делаю запрос, я получаю ошибку 404. Когда я выполняю запрос Postman, используя те же данные для POST, я получаю положительный результат.

Ниже приведен JSON, который я отправляю в API с помощью Postman.

 {
  "ActionId": null,
  "AgentCode": "MerchantCode:Password",
  "Mpin": null,
  "Amount": 0.0,
  "CustomerMSISDN": null,
  "ServiceId": 0,
  "MTI": "0300",
  "TerminalId": null,
  "TransactionRef": null,
  "CustomerAccount": null,
  "CustomerData": null,
  "Product": null,
  "ServiceProvider": "Yomoney",
  "Source": null,
  "PaymentMethod": null,
  "ProcessingCode": "420000",
  "Quantity": null,
  "OrderLines": null,
  "Narrative": null,
  "Note": null,
  "MaxSale": 0.0,
  "MinSale": 0.0,
  "TransactionType": 2
}
  

и это URL, который я отправляю на:

 https://www.yomoneyservice.com/yoclient/transaction 
  

и это ответ, который я получаю

 {"ResponseCode":"00000","Description":null,"Balance":null,"TransactionCode":null,"vouchers":null,"AgentCode":null,"Mpin":null,"Amount":0,"MaxSale":0,"MinSale":0,"CustomerMSISDN":null,"ServiceId":0,"MTI":null,"TerminalId":null,"TransactionRef":null,"TransactionType":0,"CustomerAccount":null,"CustomerData":null,"Product":null,"Quantity":0,"Action":null,"ProcessingCode":null,"Note":"Purchase","Narrative":"[{"Id":"1","Name":"THE
REDEEMED
SOLDIER","Value":"12","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":12,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"BUY
VOUCHER","Value":"10","Note":"Supplier","Image":"~/Content/Logos/YOMONEY/yomoney_v_logo.png","Description":null,"Section":null,"ServiceId":10,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"ECONET
PINLLESS","Value":"8","Note":"Supplier","Image":"~/Content/Logos/YOMONEY/buddie.png","Description":null,"Section":null,"ServiceId":8,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"TELECEL
PINLESS","Value":"3","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":3,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"Econet","Value":"2","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":2,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":true,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"NETONE
PINLESS","Value":"1","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":1,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"THE
REDEEMED
SOLDIER","Value":"12","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":12,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"BUY
VOUCHER","Value":"10","Note":"Supplier","Image":"~/Content/Logos/YOMONEY/yomoney_v_logo.png","Description":null,"Section":null,"ServiceId":10,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"ECONET
PINLLESS","Value":"8","Note":"Supplier","Image":"~/Content/Logos/YOMONEY/buddie.png","Description":null,"Section":null,"ServiceId":8,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"TELECEL
PINLESS","Value":"3","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":3,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"Econet","Value":"2","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":2,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":true,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false},{"Id":"1","Name":"NETONE
PINLESS","Value":"1","Note":"Supplier","Image":null,"Description":null,"Section":null,"ServiceId":1,"Currency":null,"ActionId":1,"TransactionType":0,"SupplierId":null,"Amount":null,"Count":0,"date":"0001-01-01T00:00:00","WebLink":null,"HasProducts":false,"IsAdvert":false,"IsNotAdvert":false,"IsShare":false,"RequireVerification":false,"RequiresRegistration":false,"RequiresAmount":false}]"}
  

Теперь, в C # я использую WebRequest amp; WebResponse, но я получаю ошибку 404, в которой говорится: «Удаленный сервер вернул ошибку: (404) Не найден.». Ниже приведен мой код C #

 try
            {
                string url = String.Format("https://www.yomoneyservice.com/yoclient/transaction");
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";                        
                
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = JsonConvert.SerializeObject(yomoneyRequest, Formatting.Indented);

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        yomoneyResponse = JsonConvert.DeserializeObject<YomoneyResponse>(result);
                    }
                }                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
  

Я больше не уверен, где я ошибаюсь в своем коде C #, кто-нибудь может мне помочь?

Ответ №1:

Я попытался воспроизвести ваш вариант использования как в коде, так и в postman. Ваше наблюдение верно, оно работает в postman, но не в коде C #.

Затем я наблюдаю разницу между запросами, отправляемыми из code и postman. Разница в cookie.

Postman отправляет один файл cookie с именем «AspxAutoDetectCookieSupport», который имеет значение «1».

Затем я изменил ваш код, чтобы добавить cookie также при отправке запроса в API, и это сработало нормально.

Чтобы добавить cookie в HttpWebRequest, вам нужно использовать CookieContainer.

Вам нужно инициализировать CookiContainer свойство HttpWebRequest и добавить к нему cookie.

Вам нужно изменить свой код следующим образом.

 try
{

    string url = String.Format("https://www.yomoneyservice.com/yoclient/transaction");
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST"; 
    httpWebRequest.CookieContainer = new CookieContainer();
    Cookie c = new Cookie("AspxAutoDetectCookieSupport", "1");
    c.Domain = "www.yomoneyservice.com";
    httpWebRequest.CookieContainer.Add(c);  
    string json = JsonConvert.SerializeObject(yomoneyRequest, Formatting.Indented);
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(json);
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        var yomoneyResponse = JsonConvert.DeserializeObject<YomoneyResponse>(result);
    } 
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}
  

Я надеюсь, что это поможет вам решить вашу проблему.

Комментарии:

1. большое вам спасибо. Ваше решение сработало просто отлично! Я бы никогда не подумал о cookie.