How can I encode string with http web request? - c#

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"

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");

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

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);

Extract Parameter from Url

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();

Replace URL in a string

I'm a beginner in C# and I have the following string,
string url = "svn1/dev";
along with,
string urlMod = "ato-svn3-sslv3.of.lan/svn/dev"
I want to replace svn1 in url with "ato-svn3-sslv3.of.lan"
Although your question still has some inconsistent statements, I believe String.Replace is what you are looking for:
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
url = url.Replace("svn1","ato-svn3-sslv3.of.lan");
Strings are immutable so you need to assign the return value to a variable:
string replacement = "ato-svn3-sslv3.of.lan";
url = url.Replace("svn1", replacement);
You can use the string method replace.
url = url.Replace("svn1", urlMod)
I think you need this:
string url = "svn1/dev";
string anotherUrl = "ato-svn3-sslv3.of.lan/svn/dev";
string toBeReplaced = anotherUrl.Split('/')[0];
url = url.Replace("svn1", toBeReplaced);
It uses split method and replace method.

Categories