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
Related
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");
I have an application where uses post comments. Security is not an issue.
string url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment
What i want is to extract the userid and comment from above string.
I tried and found that i can use IndexOf and Substring to get the desired code BUT what if the userid or comment also has = symbol and & symbol then my IndexOf will return number and my Substring will be wrong.
Can you please find me a more suitable way of extracting userid and comment.
Thanks.
I got url using string url =
HttpContext.Current.Request.Url.AbsoluteUri;
Do not use AbsoluteUri property , it will give you a string Uri, instead use the Url property directly like:
var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
and then you can extract each parameter like:
Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);
For other cases when you have string uri then do not use string operations, instead use Uri class.
Uri uri = new Uri(#"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");
You can also use TryCreate method which doesn't throw exception in case of invalid Uri.
Uri uri;
if (!Uri.TryCreate(#"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
//Invalid Uri
}
and then you can use System.Web.HttpUtility.ParseQueryString to get query string parameters:
var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
The ugliest way is the following:
String url = "http://example.com/xyz/xyz.html?userid=xyz&comment=Comment";
usr = url.Split('?')[1];
usr= usr.Split('&')[0];
usr = usr.Split('=')[1];
But #habib version is better
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);
I have a winform application, and I would like to parse a string that represent an URL to extract some parameters.
a sample of the URL is this:
http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e
the parameter I would like to extract is 271443634510 (that is, the last part of the path before the query string).
Any idea ho how this can be done?
You can use Uri.Segments, which splits up the stuff after your domain into an array that includes, for your example:
/
itm/
Sector-Watch/
271443634510
So all you need to get is the item at index 3. Working example:
string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
Uri uri = new Uri(url);
var whatYouWant = uri.Segments[3];
You can do this:
string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string parameter = Regex.Match(url,"\d+(?=\?)|(?!/)\d+$").Value;
You can simply use Split function (tested and verified):
string MyUrl="http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string str=MyUrl.Split('/').Last().Split('?').First();
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.