0

I have one URL with some special characters like | and &. URL is returning JSON data.

When I am trying this URL in browser it will run and return json data but when I am trying using WebClient.DownloadString(), it will not work.

Example :

Using Browser :

http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00

Output : 
[{"Column1":106,"Column2":"Buying Successfully."}]

Using WebClient.DownloadString():

    using (WebClient wc = new WebClient())
    {
       var json = wc.DownloadString("http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00");

    }

Output : 
[{"Column1":-107,"Column2":"Invalid Parametrer Required-(RefNo|JBPrice)!"}]
  • 2
    show code please, else no one can help you – lordkain Aug 29 '16 at 08:42
  • Welcome to StackOverflow, I think you should clarify your question a bit with examples of what you have tried so far, and what output you are expecting. See [how to ask a question.](http://stackoverflow.com/help/how-to-ask) – Roman Marusyk Aug 29 '16 at 08:44
  • Could you please take a look at: http://stackoverflow.com/questions/5566942/how-to-get-a-json-string-from-url How to get a json string from url? – huse.ckr Aug 29 '16 at 08:44
  • I think I've a similar problem, see https://stackoverflow.com/questions/72715042/c-sharp-webclient-get-html-as-string-with-parameters-in-url. Did you found a solution for it? – Wollmich Jun 22 '22 at 15:13

2 Answers2

1

You should encode PacketList parameter in your URL, because it includes pipe character, which must be encoded to %7c. Browsers automatically encode necessary characters in URL, but you should encode it in code manually.

    var json = wc.DownloadString("http://websvr.test.com/abc.aspx?Action=B&PacketList=" + 
                  System.Web.HttpUtility.UrlEncode("116307638|1355.00");
Halis S.
  • 446
  • 2
  • 11
0

Try to set webclient's encoding before call DownloadString() and encode url using UrlEncode Method :

WebClient.Encoding = Encoding.UTF8;
var url = WebUtility.UrlEncode("http://websvr.test.com/abc.aspx?Action=B&PacketList=116307638|1355.00");
var json = wc.DownloadString(url);
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • I am also trying WebClient.Encoding = Encoding.UTF8; but not working. – Nikhil Sangani Aug 29 '16 at 09:45
  • @NikhilSangani Blanl value? But in the question you wrote that you got: `[{"Column1":-107,"Column2":"Invalid Parametrer Required-(RefNo|JBPrice)!"}]`. So, what did you get in response? – Roman Marusyk Aug 29 '16 at 10:15
  • 1
    sorry MegaTron, I got [{"Column1":-107,"Column2":"Invalid Parametrer Required-(RefNo|JBPrice)!"}], but when i put url in browser it works fine. i think problem is " | " character. – Nikhil Sangani Aug 29 '16 at 10:19