ISO-8859 encode post request content C# - c#

I am trying to send a POST request in C# with a parameter encoded to ISO-8859. I am using this code:
using (var wb = new WebClient())
{
var encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
var encodedText = System.Web.HttpUtility.UrlEncode("åæ ÆÆ øØ ø", encoding);
wb.Encoding = encoding;
wb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var data = new NameValueCollection();
data["TXT"] = encodedText;
var response = wb.UploadValues(_url, "POST", data);
}
I have figured out that the correctly encoded string for "åæ ÆÆ øØ ø" is %E5%E6+%C6%C6++%F8%D8+%F8, and I can see when debugging that encodedText actually is this string. However when inspecting the raw request in fiddler, I can see that the string looks like this: TXT=%25e5%25e6%2B%25c6%25c6%2B%25f8%25d8%2B%25f8. I am guessing some kind of extra encoding is being done to the string after or during the call to UploadValues().
Thank you so much in advance.

I checked Google for this. According to another question here on SO at UTF32 for WebClient.UploadValues? (second answer), Webclient.UploadValues() indeed does encoding itself. However, it does ASCII encoding. Youll have to use another method to upload this, like HttpWebRequest.

Related

WebClient.DownloadString doesn't return value

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)!"}]
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");
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);

unable to decode Icelandic dual byte character in response string of .net appliaction

I have an application build on c#. here is the snippet of my code
private void ProcessRequest(IAsyncResult result)
{
HttpListenerContext context = httpListener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
NameValueCollection queryString = getQueryStringFromRequest(request);
…….
}
The response I get is in English only. However, sometimes I get part of the response in other language, Like Icelandic. Then my application is not able to format the string accordingly. For example in queryString I get something like this:
{ ENTITY_NAME=Contact&OBJECT_NAME=Mr.+Hl%ufffd%ufffdar+Hl%ufffd%ufffdberg}
However object name should be Mr. Hlíðar Hlíðberg.
I understand that issue is with not able to parse it according to dual byte character. I tried something similar to:
if (queryString["OBJECT_NAME"] != null){
string s_unicode = queryString["OBJECT_NAME"];
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;
byte[] utfBytes = utf_8.GetBytes(s_unicode);
byte[] isoBytes = Encoding.Convert(utf_8, iso_8859_1, utfBytes);
string msg = iso_8859_1.GetString(isoBytes);
}
but still i am getting response like Mr. Hl??ar Hl??berg
but it didn’t worked for me. Also i never liked this method as its to specific and things needs to be hard coded for eg. the key in this case.
So, How do I do it. Can I do something through config file or generic?

Send POST with WebClient.DownloadString in C#

I know there are a lot of questions about sending HTTP POST requests with C#, but I'm looking for a method that uses WebClient rather than HttpWebRequest. Is this possible? It'd be nice because the WebClient class is so easy to use.
I know I can set the Headers property to have certain headers set, but I don't know if it's possible to actually do a POST from WebClient.
You can use WebClient.UploadData() which uses HTTP POST, i.e.:
using (WebClient wc = new WebClient())
{
byte[] result = wc.UploadData("http://stackoverflow.com", new byte[] { });
}
The payload data that you specify will be transmitted as the POST body of your request.
Alternatively there is WebClient.UploadValues() to upload a name-value collection also via HTTP POST.
You could use Upload method with HTTP 1.0 POST
string postData = Console.ReadLine();
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// Upload the input string using the HTTP 1.0 POST method.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
byte[] byteResult= wc.UploadData("http://targetwebiste","POST",byteArray);
// Decode and display the result.
Console.WriteLine("\nResult received was {0}",
Encoding.ASCII.GetString(byteResult));
}

Using google translate api POST method, returns 404

So basically I have some french text and want to traduce it in english using c#.
I'm using google translate api, which was working fine until i had a text.length > 1000 .... then I realized that I must use POST method.
Since I use the post method, it returns me 404.
btw i know the api is deprecated, I though it would be cool anyways but I'm starting to realize maybe i should use bing ?
string fromLanguage = "fr";
string toLanguage = "en";
String apiKey = "AIzasdfasdfJvWKNioZwLg-3kyYsm4_dao";
String apiUrl = "https://www.googleapis.com/language/translate/v2";
string tmpTranslatedContent = Translate(apiUrl, "salut la planete", apiKey, fromLanguage, toLanguage);
public string Translate(string url, string text, string key, string fromLanguage, string toLanguage)
{
PostSubmitter post = new PostSubmitter();
post.Url = url;
post.PostItems.Add("key", key);
post.PostItems.Add("source", fromLanguage);
post.PostItems.Add("target", toLanguage);
post.PostItems.Add("q", text);
post.Type = PostSubmitter.PostTypeEnum.Post;
string result = post.Post();
return result;
}
PostSubmitter is a class i found when searching google
Comments on the site are saying it works.....
the main part of the class looks like this
HttpWebRequest request=null;
if (m_type==PostTypeEnum.Post)
{
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
thanks.
This is a little old, but I just ran into a similar problem but with PHP instead of C# and the fix should be quite similar.
Basically, even though you are using POST, you still need to tell Google that from a REST point of view you are actually doing a GET. This can be done with the X-HTTP-Method-Override header, setting it to be: X-HTTP-Method-Override: GET
Google tells me that as ASP.NET MVC, version 2, there is a method HttpHelper.HttpMethodOverride that will allow you to do this.
According to the Google Translate API however, text is still limited to 5k even when posting.

HttpWebRequest: How to find a postal code at Canada Post through a WebRequest with x-www-form-enclosed?

I'm currently writing some tests so that I may improve my skills with the Internet interaction through Windows Forms. One of those tests is to find a postal code which should be returned by Canada Post website.
My default URL setting is set to: http://www.canadapost.ca/cpotools/apps/fpc/personal/findByCity?execution=e4s1
The required form fields are: streetNumber, streetName, city, province
The contentType is "application/x-www-form-enclosed"
EDIT: Please consider the value "application/x-www-form-encoded" instead of point 3 value as the contentType. (Thanks EricLaw-MSFT!)
The result I get is not the result expected. I get the HTML source code of the page where I could manually enter the information to find the postal code, but not the HTML source code with the found postal code. Any idea of what I'm doing wrong?
Shall I consider going the XML way? Is it first of all possible to search on Canada Post anonymously?
Here's a code sample for better description:
public static string FindPostalCode(ICanadadianAddress address) {
var postData = string.Concat(string.Format("&streetNumber={0}", address.StreetNumber)
, string.Format("&streetName={0}", address.StreetName)
, string.Format("&city={0}", address.City)
, string.Format("&province={0}", address.Province));
var encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request = (HttpWebRequest)WebRequest.Create(DefaultUrlSettings);
request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Anonymous;
request.Container = new CookieContainer();
request.Timeout = 10000;
request.ContentType = contentType;
request.ContentLength = postDataBytes.LongLength;
request.Method = #"post";
var senderStream = new StreamWriter(request.GetRequestStream());
senderStream.Write(postDataBytes, 0, postDataBytes.Length);
senderStream.Close();
string htmlResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
return processedResult(htmlResponse); // Processing the HTML source code parsing, etc.
}
I seem stuck in a bottle neck in my point of view. I find no way out to the desired result.
EDIT: There seems to have to parameters as for the ContentType of this site. Let me explain.
There's one with the "meta"-variables which stipulates the following:
meta http-equiv="Content-Type" content="application/xhtml+xml,
text/xml, text/html; charset=utf-8"
And another one later down the code that is read as:
form id="fpcByAdvancedSearch:fpcSearch" name="fpcByAdvancedSearch:fpcSearch" method="post" action="/cpotools/apps/fpc/personal/findByCity?execution=e1s1" enctype="application/x-www-form-urlencoded"
My question is the following: With which one do I have to stick?
Let me guess, the first ContentType is to be considered as the second is only for another request to a function or so when the data is posted?
EDIT: As per request, the closer to the solution I am is listed under this question:
WebRequest: How to find a postal code using a WebRequest against this ContentType=”application/xhtml+xml, text/xml, text/html; charset=utf-8”?
Thanks for any help! :-)
I'm trying to see a reason why you are not using the WebClient class:-
var fields = new NameValueCollection();
fields.Add("streetnumber", address.StreetNumber);
fields.Add("streetname", address.StreetName);
fields.Add("city", address.City);
fields.Add("province", address.Province);
var wc = new WebClient();
byte[] resultData = wc.UploadValues(url, fields);
string result = Encoding.Default.GetString(resultData);
You might want to check the encoding used by the server when sending the results, if it uses UTF-8 change the last line to:-
string result = Encoding.UTF8.GetString(resultData);
Some issues I spot in your orginal code:-
The first field is prefixed with &, that shouldn't be there.
You need call use Uri.EscapeDataString on each field value.
You are attempting to construct a memory stream around the result of GetRequestStream, I can't see what that would achieve even if MemoryStream had such a constructor but it doesn't anyway. Just write directly to the stream returned by GetRequestStream
If you have already done so get yourself a copy of fiddler so you can observe what occurs when a standard form requests the data sucessfully and what your code is doing.
Edit: If you have evidence that the lack of a cookie container is what causes WebClient not to work then you could try this approach:-
public class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest (Uri address)
{
WebRequest request = (WebRequest) base.GetWebRequest (address);
request.Container = new CookieContainer();
return request;
}
}
Now use my code above to but instead od instancing WebClient instance MyWebClient instead.
HTTPWebRequest will return the content of the URLrequested. If it is a HTML page, it will return HTML markup. If the page content is XML, then it will return XML markup.
It sounds like you need is a Webservice. I would see if that site has any webserivces available to process that type of request. If they do, then it will return XML, JSON markup in response to your query. Otherwise you are left to parsing the output of the request.

Categories