i think i am going a bit crazy, when i test this on my local webserver, it works fine
when i go out to the live website, it returns a blank string instead of the data i am expecting
i am not that familiar with C#, so i just wanted to check i am doing things right.
the data is just plain ascii text
wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
response = wc.UploadData(this.urlUpdate, Encoding.ASCII.GetBytes("data=" + HttpUtility.UrlEncode(buf.ToString())));
s = Encoding.ASCII.GetString(response);
It really depends what you are trying to do... I'm not sure, for example, why you are url-encoding data in the body. An easier way to post key/value pairs is with UploadValues;
NameValueCollection inputs = new NameValueCollection();
string value = ...
inputs.Add("data", value);
webClient.UploadValues(address, inputs);
Related
I have some C# code that does the following post request:
string postData = newFormUrlEncodedContent(params).ReadAsStringAsync().Result;
var postContent = new StringContent(postData, UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
var responseMessage = httpClient.PostAsync(url, postContent).Result;
I would like to do the equivalent in Python using the Requests library. This is what I have:
headers = {'content-type':'application/x-www-form-urlencoded'}
postContent = requests.post(url, params=params, headers=headers, cookies=previousResponse.cookies)
But postContent.status_code for the Python code is 404, whereas the C# request returns 200. It's possible that there's something wrong with the params since I retrieve those via some Regex matching from a previous request, but that seems to be working.
Edit: I think setting the params parameter is for get requests, not post requests. Also I believe Requests takes care of form encoding:
Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made
So now I have:
postContent = requests.post(url, data = params, cookies = previousResponse.cookies)
Now postContent.status_code == 500. The stack trace says the data is invalid at the root level. I will look into it.
I have website which gives me different value (example: value="c04f8d84708f9865f4e04802c51c2f90") every time when I clear cookies in my standard browsers (Firefox, Chrome...).
But when I use client I get always same value, my code:
WebClient client1 = new WebClient();
client1.Headers.Add("Cache-Control", "no-cache");
client1.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
string html = client1.DownloadString("website");
client1.Dispose();
How I can clear all data/cookies so I can get different value ?
Have you tried this:
httpClient.DefaultRequestHeaders.Accept.Clear();
use HttpRequest object instead of WebClient, and hopefully (if you place your doubts in WebClient) everything will be solved. If it wasn't solved with HttpRequest, then the problem really IS somewhere else.
Hope this helps.
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
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.
i'm trying to invoke a webapi with the new System.Net.WebClient and didnot found any special examples.
The goal is simulate a traditional form post with some fields and a file.
how can i do it using the System.Net.WebClient or where can i find some examples?
thanks in advance
I think you need this:
http://dzimchuk.net/post/uploading-a-file-over-http-in-net
This is a very well written blog. See the last example.
There are a lot of examples if you do a fast google search, anyway, here goes some samples:
Simple GET
WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json"; //setting headers
string json = webClient.DownloadString(url);
Simple POST
NameValueCollection values = new NameValueCollection();
values["user"] = username;
values["pwd"] = password;
webClient.UploadValues(url, values);
There's also an UploadData that sends byte arrays and UploadFile that allows you to upload files directly from disk.