pepeortiz
pepeortiz

Reputation: 5

HttpWebRequest request with "?" in the API URL

I am trying to fetch an API REST response but the API's URL has an "?" in the URL (see example below).

HttpWebRequest request = WebRequest.Create("http://api.mydomain.com/news/?tag=sports") as HttpWebRequest;

Is there a way to escape this?

I tried Uri.EscapeUriString and HttpUtility.HtmlEncode but that is not working either.

Any ideas?

Upvotes: 0

Views: 3052

Answers (3)

Leonardo Arruda
Leonardo Arruda

Reputation: 261

First you must create the request with url without params.

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://api.mydomain.com/news/");
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

After this you create a string to post the params.

        strParams = "tag=" + strTag; 
        req.ContentLength = strSaida.Length;

Then write it.

        stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
        stOut.Write(strParams);
        stOut.Close();

Is that what you need?

Upvotes: 1

Telmo Marques
Telmo Marques

Reputation: 5104

Try passing a Uri object instead of a string to the Create()method.

HttpWebRequest request = WebRequest.Create(new Uri("http://api.mydomain.com/news/?tag=sports")) as HttpWebRequest;

How to add query string to httpwebrequest

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You don't need to escape anything. The ? is what separates the path portion of the url from the query string portion. http://api.mydomain.com/news/?tag=sports is a perfectly valid url.

Or maybe your API expects: http://api.mydomain.com/news/sports? Difficult to say without knowing which API you are trying to consume.

Upvotes: 1

Related Questions