How to send a request with data using System.Net.HttpWebRequest - c#

I want to send simple GET request using System.Net.WebRequest. But i have a problem when I try to send on URL-s that contains "Space" character.
What i do:
string url = "https://example.com/search?text=some words&page=8";
var webRequest = System.Net.WebRequest.Create(link) as HttpWebRequest;
If i try to use this code, then webRequest.Address == "https://example.com/search?&text=some words&page=8" (#1)
I can manually add "%20" for UrlEncoded space, but "WebRequest.Create" decodes it, and again i have (#1). How can i do it right?
P.S. sorry for my English.

Try a plus sign (+) instead of space. Also drop the first ampersand (&); it is only used on non-primary arguments. As in
var url = "https://example.com/search?text=some+words&page=8";

You should make parameter values "url-friendly". To achieve that, you must "url-encode" values, using HttpUtility.UrlEncode(). This fixes not only spaces, but many other dangerous "quirks":
string val1 = "some words";
string val2 = "a <very bad> value & with specials!";
string url = "https://example.com/search?text=" + HttpUtility.UrlEncode(val1) + "&comment=" + HttpUtility.UrlEncode(val2);

Related

HttpUtility.UrlEncode unexpected output

Iam trying to encode a url, so that the HttpWebRequest is fine with characters like &.
So google bring me up to this:
url = HttpUtility.UrlEncode(url);
But this makes the whole url unuseable. Iam getting Status-Error: Invalid Operation from Web-Server.
I got this url before iam using encoding:
http://jira-test.myServer.de/rest/api/2/search?jql=labels = "F&E"
After encoding i got this:
http%3a%2f%2fjira-test.brillux.de%2frest%2fapi%2f2%2fsearch%3fjql%3dlabels+%3d+%22F%26E%22
What iam doing wrong? In my opinion it shouldn't replace the // after http and so on... Or is there another way to handle this issue?
Info:
Uri.EscapeDataString();
gives me the same result.
You should only be encoding the values of your query string, not the entire URI:
var uri = "http://jira-test.myServer.de/rest/api/2/search?jql=" +
HttpUtility.UrlEncode("labels = \"F&E\"");
// Result: http://jira-test.myServer.de/rest/api/2/search?jql=labels+%3d+%22F%26E%22
The proper way to construct this:
// Construct query string using HttpValueCollection, which handles escaping:
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString.Add("jql", "labels = \"F&E\"");
// Combine base URI with query string through UriBuilder:
var uriBuilder = new UriBuilder("http://jira-test.myServer.de/rest/api/2/search");
uriBuilder.Query = queryString.ToString();
// Get string representation:
string uri = uriBuilder.ToString();
// Result: http://jira-test.myserver.de:80/rest/api/2/search?jql=labels+%3d+%22F%26E%22

When sending XML by POST, the symbol & is escaping entire rest of string

I am trying to pass a string formatted as XML to a Web Api controller, and when it is sent, it only receives the string up to the first & symbol, and then cuts off. Is there any way to make sure the & symbols will not escape the string?
Here is an example of my request:
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string allLines = "=" + param.ToString();
result = client.UploadString(url, "POST", allLines);
}
return result;
HTTP header sometimes is not just key-value pair. It can be an array of values divided by & character.
Try to use HttpUtility.UrlEncode(value) when sending value and HttpUtility.UrlDecode(value) when receiving.
Try Uri.EscapeUriString or HttpUtility.UrlPathEncode. Alternately, you can manually encode an ampersand by replacing it with %26. For instance:
myString.Replace("&", "%26");

get Request.QueryString as it show

VerifyEmail.aspx?key=KMSO+tLs5zY=&val=ALKXZzxNxajUWVMaddKfPG/FcFD111CD
Request.QueryString["key"].ToString() gives me "KMSO tLs5zY="
i want key value "KMSO+tLs5zY="
If you can modify the url parameter, you can encode the values using the HttpUtility.UrlEncode method, for example:
string url = "VerifyEmail.aspx?key=" + HttpUtility.UrlEncode("KMSO+tLs5zY=");
Another method is to use Base64 encoding
string url = "VerifyEmail.aspx?key=" + EncodeTo64("KMSO+tLs5zY=");
and decoding the value reading the querystring
String value = DecodeFrom64(Request["key"]);
the code for the EncodeTo64 and DecodeFrom64 is available in this article http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/
Do not use %2B instead of + when producing url.
And if you get %2B's itself when requesting, do not try to replace it using
Request.QueryString["key"].ToString().Replace("%2B","+")
Use HttpUtility class' UrlEncode() method:
HttpUtility.UrlEncode("KMSO+tLs5zY=")
(:

How can I parse HTTP urls in C#?

My requirement is to parse Http Urls and call functions accordingly. In my current implementation, I am using nested if-else statement which i think is not an optimized way. Can you suggest some other efficient approch?
Urls are like these:
server/func1
server/func1/SubFunc1
server/func1/SubFunc2
server/func2/SubFunc1
server/func2/SubFunc2
I think you can get a lot of use out of the System.Uri class. Feed it a URI and you can pull out pieces in a number of arrangements.
Some examples:
Uri myUri = new Uri("http://server:8080/func2/SubFunc2?query=somevalue");
// Get host part (host name or address and port). Returns "server:8080".
string hostpart = myUri.Authority;
// Get path and query string parts. Returns "/func2/SubFunc2?query=somevalue".
string pathpart = myUri.PathAndQuery;
// Get path components. Trailing separators. Returns { "/", "func2/", "sunFunc2" }.
string[] pathsegments = myUri.Segments;
// Get query string. Returns "?query=somevalue".
string querystring = myUri.Query;
This might come as a bit of a late answer but I found myself recently trying to parse some URLs and I went along using a combination of Uri and System.Web.HttpUtility as seen here, my URLs were like http://one-domain.com/some/segments/{param1}?param2=x.... so this is what I did:
var uri = new Uri(myUrl);
string param1 = uri.Segments.Last();
var parameters = HttpUtility.ParseQueryString(uri.Query);
string param2 = parameters["param2"];
note that in both cases you'll be working with strings, and be specially weary when working with segments.
I combined the split in Suncat2000's answer with string splitting to get at interesting features of the URL. I am passing in a full Uri including https: etc. from another page as the navigation argument e.Parameter:
Uri playlistUri = (Uri)e.Parameter;
string youtubePlaylistUnParsed = playlistUri.Query;
char delimiterChar = '=';
string[] sections = youtubePlaylistUnParsed.Split(delimiterChar);
string YoutubePlaylist = sections[1];
This gets me the playlist in the PLs__ etc. form for use in the Google APIs.

How can I encode string with http web request?

I need to send a string to a website and get back a result.
But for example if i send "hello world" it should be "hello%world" instead of space there should be a %
There should be a way i think to make it automatic so it will know where how and when to put this % when the string have spaces in this location.
For example i have this string which is a site url:
https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de
There is a %20 between the hello and the world. How can i do it ?
You could use the ParseQueryString method to build a properly encoded query string:
var values = HttpUtility.ParseQueryString(string.Empty);
values["key"] = "INSERT-YOUR-KEY";
values["q"] = "hello world";
string queryString = values.ToString();
// at this stage queryString="key=INSERT-YOUR-KEY&q=hello+world"
You can use HttpUtility.UrlEncode:
string s = "Hello World";
string t = HttpUtility.UrlEncode(s);//t becomes "Hello+World"

Categories