Hi I am trying to send a data up to a web service via a WebClient but it seems to be incorrectly passing through the password field. Here is the code below for my WebClient:
using (var client = new WebClient())
{
client.Encoding = System.Text.Encoding.UTF8;
var response = client.UploadString(string.Format(SendToServiceURL + "api/SendRequest?Id={0}&product={1}&password={2}", Id, Product, Password),
"POST");
return response;
}
The password before sending is - GVg4Vs2<)/BFkU(u%Be%C:{<^9
However the password when received by the service is - GVg4Vs2<)/BFkU(u�%C:{<^9
I have also tried making use of the HTTP utility pack HtmlEncode feature as shown below but that only returned GVg4Vs2.
(Note I just substituted Password in my original code for the encodedPassword variable below)
var encodedPassword = HttpUtility.HtmlEncode(password);
Does anyone have an idea of why this is or a possible workaround?
You need to use HttpUtility.UrlEncode instead of HttpUtility.HtmlEncode.
HtmlEncode turns < into < which means everything after & is a new query string parameter.
UrlEncode makes sure all the "weird" characters can be passed correctly as a query string parameter: GVg4Vs2%3c)%2fBFkU(u%25Be%25C%3a%7b%3c%5e9
But preferably you shouldn't put a password in the query string at all but make it part of the post data or even better use a proper authentication mechanism for the webservice call.
Related
I'm trying to send special characters through an http request, now I'm using Loopj as my http client. The problem is that when I try to send special characters i.e. "áéíóú" the request goes out with the characters "·ÈÌÛ˙", this is causing some issues on the server sider.
I've gone through the Loopj code and couldn't find anything relative to recoding my string or anything like it. In the worst case it seems like it would be encoded in UTF-8 which actually supports this characters.
Hope anyone can help.
Best Regards.
I am guessing you mean AsyncHttpClient library, correct?
AHC defaults to encoding all I/O in UTF-8. Due to the lack of source code, I would point you to investigate the following:
What is the encoding of the input? Make sure it's in UTF-8.
Are you running the input through a filter/function that might change its encoding? Make sure that the filter/function produces UTF-8 also.
Prior to checking what your backend actually receives, change your client to submit to http://httpbin.org/post and then check the result.
If you receive correct submission in httpbin, and bad submission in your backend, the problem is NOT in AHC but in your backend.
If you receive bad submissions in both httpbin and the backend, then the data being sent was originally bad or in a wrong encoding.
I hope this helps you find the problem quickly.
Why Don't you use this Approach:
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(httpParameters);
client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
client.getParams().setParameter("http.socket.timeout", new Integer(2000));
client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
httpParameters.setBooleanParameter("http.protocol.expect-continue", false);
HttpPost request = new HttpPost("http://www.server.com/some_script.php?sid=" + String.valueOf(Math.random()));
request.getParams().setParameter("http.socket.timeout", new Integer(5000));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// you get this later in php with $_POST['value_name']
postParameters.add(new BasicNameValuePair("value_name", "value_val"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String lineSeparator = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append(lineSeparator);
}
in.close();
String result = sb.toString();
Users of above code says, this code works like charm. And i think if you are facing issues with your approach then you should change your approach to solve your problem.
See this Link which i found useful for you: Android default charset when sending http post/put - Problems with special characters
I'm constructing an NSUrlSession as follows:
NSUrlSessionConfiguration sessionCfg = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("mySpecialSessionName");
NSUrlSessionDelegate sessionDelegate = new MySessionDelegate();
urlSession = NSUrlSession.FromConfiguration(sessionCfg, sessionDelegate, NSOperationQueue.MainQueue);
And invoking background downloads with custom HTTP headers:
NSMutableUrlRequest mutableRequest = new NSMutableUrlRequest();
mutableRequest.HttpMethod = "POST";
mutableRequest.Url = NSUrl.FromString(someEndpoint);
mutableRequest["MyCustomHeader"] = someStringWithUnicodeChars;
mutableRequest.Body = NSData.FromString(somePostBody);
NSUrlSessionDownloadTask downloadTask = m_UrlSession.CreateDownloadTask(mutableRequest);
downloadTask.Resume();
However, the header value string seems to get truncated at the first character above 255. For example, the header value:
SupeЯ Σario Bros
is received by the server as
Supe
When instead using .NET HttpClient on xamarin, unicode header strings successfully make it to the server unmodified. However, I'd like to make use of NSUrlSession's background downloading feature.
(I realize that support of unicode in HTTP headers is hit-and-miss, but since the HTTP server in this case is a particular custom server that doesn't currently support things like base64 encoding, passing the raw string is desired)
I don't know whether you'll be able to make that work, but two things come to mind:
What you have here is equivalent to calling setValue:forKey: on the URL request. I don't think that will do what you're expecting. Try calling the setValue:forHTTPHeaderField: method instead.
Try specifying the encoding before you specify your custom header value, e.g. [theRequest setValue:#"...; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
If neither of those helps, you'll probably have to encode the data in some way. I would suggest using URL encoding, because that's a lot simpler to implement on the server side than Base64. For the iOS side, see this link for info on how to URL-encode a string:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html
I have a problem with sending data from ASP with the POST Method to a PHP page.
I would like to send mail with names. And since I live in Austria the names are in German and we have some Special characters. These characters don't arrive write.
I'm still pretty new to programming with C# btw. I had the Website before in Java-Script but I had to connect it with a database and therefore I switched to C# and now I'm like a "babe in the woods".
this.hdnDaten.Value = "ÄÖÜ|äöü|ß|é|#";
// mit POST versuchen
using (var client = new WebClient())
{
var postData = new System.Collections.Specialized.NameValueCollection();
postData.Add("von", this.hdnVon.Value);
postData.Add("an", this.hdnAn.Value);
postData.Add("betreff", this.hdnBetreff.Value);
postData.Add("daten", this.hdnDaten.Value);
byte[] response = client.UploadValues("http://xxxxxx.php", "POST", postData);
var responsebody = Encoding.UTF8.GetString(response);
}
And this is how the characters (in this.hdnDaten.Value) from above arrive in the mail-body:
ÄÖÜ|äöü|ß|é|#
Does anybody know what I can do to get the same characters in the end?
Edit 20143013: I think I have a clue: I have to encode the postData into ANSI (Codepage 1252). I tried do do this, but it doesn't work. Does anybody have an Idea how I could do this?
Edit 20140320: I don't even dare to give you the answer: I was looking all the time in the wrong place (somewhat like MH370): The problem was with the receiving side of the mail (I was using a POP3-Viewer for testing); when I downloaded the mail to Outlook everything was OK. The funny thing was that this didn't happen in the original (Javascript) Version that's why I was looking at the wrong place.
Thanks
Eddie
Try setting client.Encoding to UTF-8 before calling UploadValues. Also ensure that you read the text as UTF-8 on the server.
Try this.hdnDaten.Value = HttpUtility.UrlEncode("ÄÖÜ|äöü|ß|é|#"); on your post parameters.
on PHP you'll need to decode the parameters via html_entity_decode
I am doing a redirect from one page to another and another redirect from the second page to a third. I have imformation from the first page which is not used on the second page but must be transfered to the third page. Is it possible to send the URL of the third page with its Query Strings as a Query String to the second page. Here's an example:
Response.Redirect("MyURL1?redi=MyURL2?name=me&ID=123");
My problem is that the URL being sent as a Query String has two Query String variables, so how will the system know that what's after the & is the second variable of the second URL and not a second variable of the first URL? Thank you.
You must encode the url that you pass as a parameter in your redirect URL. Like this:
MyURL = "MyURL1?redi=" + Server.UrlEncode("MyURL2?name=me&ID=123");
This will create a correct url without the double '?' and '&' characters:
MyURL1?redi=MyURL2%3fname%3dme%26ID%3d123
See MSDN: HttpServerUtility.UrlEncode Method
To extract your redirect url from this encoded url you must use HttpServerUtility.UrlDecode to turn it into a correct url again.
Your query string should look like this:
MyURL1?redi=MyURL2&name=me&ID=123
Check: http://en.wikipedia.org/wiki/Query_string
You should have one ? sign and all parameters joined with &. If parameter values contain special characters just UrlEncode them.
I find it helpful to encode query string parameters in Base64 before sending. In some cases this helps, when you need to send all kinds of special characters. It doesn't make for good debug strings, but it will protect ANYTHING you are sending from getting mixed with any other parameters.
Just keep in mind, the other side who is parsing the query string will also need to parse the Base64 to access the original input.
using System.IO;
using System.Net;
static void sendParam()
{
// Initialise new WebClient object to send request
var client = new WebClient();
// Add the QueryString parameters as Name Value Collections
// that need to go with the HTTP request, the data being sent
client.QueryString.Add("id", "1");
client.QueryString.Add("author", "Amin Malakoti Khah");
client.QueryString.Add("tag", "Programming");
// Prepare the URL to send the request to
string url = "http://026sms.ir/getparam.aspx";
// Send the request and read the response
var stream = client.OpenRead(url);
var reader = new StreamReader(stream);
var response = reader.ReadToEnd().Trim();
// Clean up the stream and HTTP connection
stream.Close();
reader.Close();
}
I'm trying to make a server-side login process with facebook in my C# MVC application.
At the moment of submiting an status update in my app it has to publish it on facebook, I make a redirect to:
https://www.facebook.com/dialog/oauth?client_id={0}&scope={1}&redirect_uri={2}
Using this Method:
Response.Redirect(...);
where my redirect uri is encoded like this:
HttpUtility.UrlEnconde("http://local.mydomain.com/getAuthToken?message=the original message");
And back into my MVC app (after accepting the fb permissions) the getAuthToken action makes a request to the URI:
https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}
Using this Method:
using (var wc = new WebClient()){
wc.DownloadString(...)
}
where my redirect uri again is encoded like this:
HttpUtility.UrlEnconde("http://local.mydomain.com/getAuthToken?message=the original message");
if "the original message" contains no spaces it works but when I start adding spaces and other special characters I get an OAuth Exception:
Error validating verification code
So my question is, what kind of URL Enconding should I have to use to make it work
I Found something here but I'm getting the same error, I dont know if I need a special method to make the redirects or if I need diferent Encodings for this two request.
I would suggest you look at Dino Cheisa's excellent OAuth.Manager class. This does the URL Encoding properly. You can get it from http://cheeso.members.winisp.net/OAuthManager1.1/html/N_OAuth.htm
To solve this I used this to encode:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= Encoding.ASCII.GetBytes(toEncode);
string returnValue
= Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
and this to decode
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= Convert.FromBase64String(encodedData);
string returnValue =
Encoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
In case someone needs it
Thaks