The current project I am working on requires a 2 way communication from the bot to my website.
Supposing the example URL is www.example.com/foobar.php or something, can you explain me how to POST and GET data from there?
Thanks a lot.
P.S. - Using webclient right?
I'd suggest using RestSharp. It's a lot easier than using WebClient, and gives you a lot more options:
var client = new RestClient("http://www.example.com/");
//to POST data:
var postRequest = new RestRequest("foo.php", Method.POST);
postRequest.AddParameter("name", "value");
var postResponse = client.Execute(postRequest);
//postResponse.Content will contain the raw response from the server
//To GET data
var getRequest = new RestRequest("foo.php", Method.GET);
getRequest.AddParameter("name", "value");
var getResponse = client.Execute(getRequest);
Yes, you can use WebClient:
using (WebClient client = new WebClient())
{
NameValueCollection nvc = new NameValueCollection()
{
{ "foo", "bar"}
};
byte[] responseBytes = client.UploadValues("http://www.example.com/foobar.php", nvc);
string response = System.Text.Encoding.ASCII.GetString(responseBytes);
}
You can use WebClient
Look up method UploadString and DownloadString
Related
I am getting data from the discogs API. It works fine when I get a single page of results, but when I try and make a second call (to get the next page of results) I get a 403 (Forbidden) error.
using (WebClient wc = new WebClient())
{
wc.Headers.Add("user-agent", "myUserName");
var json = wc.DownloadString(String.Format("https://api.discogs.com/users/{0}/collection/folders/0/releases", username));
var json2 = wc.DownloadString(String.Format("https://api.discogs.com/users/{0}/collection/folders/0/releases?page=2", username));
}
Is this something to do with making two calls in the same using (WebClient...) block, or some other authentication issue?
The headers in WebClient are cleared after each call so you would need to re-add them, for example:
using (WebClient wc = new WebClient())
{
wc.Headers.Add("user-agent", "myUserName");
var json = wc.DownloadString(String.Format("https://api.discogs.com/users/{0}/collection/folders/0/releases", username));
wc.Headers.Add("user-agent", "myUserName");
var json2 = wc.DownloadString(String.Format("https://api.discogs.com/users/{0}/collection/folders/0/releases?page=2", username));
}
However, you should really consider using the newer, modern HttpClient instead. Even the docs for WebClient state:
We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.
I am using RestSharp to post some data to a url. I am monitoring this operation using fiddler. when I use Simple .net HttpClient with this code:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string> {
{ "par1", "1395/11/29" },
{ "par2", "2" }};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://someurl.com/resource", content);
var responseString = await response.Content.ReadAsStringAsync();
}
every thing is good and this return true result. but when i try to use RestSharp with this code:
RestSharp.RestRequest request = new RestSharp.RestRequest("/resource");
request.AddParameter("par1", val, RestSharp.ParameterType.RequestBody);
request.AddParameter("par2", val, RestSharp.ParameterType.RequestBody);
request.AddHeader("Origin", "http://someurl.com");
request.Method = RestSharp.Method.POST;
RestSharp.RestClient client = new RestSharp.RestClient("http://someurl.com");
var response = client.Execute(request);
then fiddler show me the request sent by GET method instead of POST?
I check another time my fiddler and found this issue:
Content-Type: par1
why this is happening for me?
Change your ParameterType argument to GetOrPost and it will work
request.AddParameter("par1", val, RestSharp.ParameterType.GetOrPost);
request.AddParameter("par2", val, RestSharp.ParameterType.GetOrPost);
Initialize Request as POST with JSON.
var client = new RestClient(PreUri);
var request = new RestRequest(Uri, Method.POST) {RequestFormat = DataFormat.Json};
Add object in body
request.AddBody(obj);
Execute
var cancellationTokenSource = new CancellationTokenSource();
var response = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);
I was stupidly doing mistake to call "client.Get" instead of "client.Post". May be this post helps other.
var client = new RestClient("https://someservice.com");
var request = new RestRequest("/token/", Method.POST, DataFormat.Json).AddJsonBody(SomeObject);
var response = client.Get(request);
I was expecting this code to make POST request. Because i specified it as Method.POST.
But after a few hours, i saw my mistake. Yeas i was specifying the method. But just after i am calling client.Get(request); This changes the metod to GET.
So, the right way to use POST request is like follows:
var client = new RestClient("https://someservice.com");
var request = new RestRequest("/token/", DataFormat.Json).AddJsonBody(SomeObject);
var response = client.Post(request);
I have the following python code how to post a picture through webservice:
product_image = requests.post(
'https://client.planorama.com/tapi/v1/product_image/',
data={ 'product_id': 1784682 },
files={ "file": open(my_image.jpg, 'rb') }
)
Can anyone help me to do the same thing in C#,
Multipart Form Post in C# includes a simple C# class using HttpWebRequest with a provided (working) example.
We are rather spoiled with the requests library in python.
Are you running .NET 4 or 4.5? If so, take a look at Joshcodes answer to Sending Files using HTTP POST in c# - it uses Microsoft.Net.Http which is by far the best HTTP library in the .NET world these days.
UPDATE: I haven't checked this for accuracy yet, but it could go something like this:
static HttpResponseMessage UploadFileWithParam(string requestUri, string fileName, string key1, string val1)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent(val1), key1);
var fileContent = new StreamContent(File.OpenRead(fileName));
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
return client.PostAsync(requestUri, content).Result;
}
}
}
// UploadFileWithParam("http://example.com", #"c:\...", "param1", "value1").Dump();
I have some JavaScript code that I need to convert to C#. My JavaScript code POSTs some JSON to a web service that's been created. This JavaScript code works fine and looks like the following:
var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
url: "http://www.mysite.com/1.0/service/action",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json;charset=utf-8",
success: action_Succeeded,
error: action_Failed
});
function action_Succeeded(r) {
console.log(r);
}
function log_Failed(r1, r2, r3) {
alert("fail");
}
I'm trying to figure out how to convert this to C#. My app is using .NET 2.0. From what I can tell, I need to do something like the following:
using (WebClient client = new WebClient())
{
string json = "?";
client.UploadString("http://www.mysite.com/1.0/service/action", json);
}
I'm a little stuck at this point. I'm not sure what json should look like. I'm not sure if I need to set the content type. If I do, I'm not sure how to do that. I also saw UploadData. So, I'm not sure if I'm even using the right method. In a sense, the serialization of my data is my problem.
Can someone tell me what I'm missing here?
Thank you!
The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
You need a json serializer to parse your content, probably you already have it,
for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,
I am trying to simulate a post request using WebClient; However, When logging in using Firefox and debugging the request with firebug i find that after the POST request it automatically do some GET requests while using my code only do the POST request
MY CODE
//Handler is an overridden WebClient Class
private async Task<byte[]> Post(string uri, string[] data)
{
var postData = new NameValueCollection();
foreach (var info in data.Select(var => var.Split('=')))
{
postData.Add(info[0], info[1]);
}
return await Handler.UploadValuesTaskAsync(new Uri(uri), postData);
}
I know this isn't what you are asking for, AND its in VB, but hopefully it can help to point you in the right direction. It is what I use to make post requests on one of our websites. It works for simulating the POST data, hopefully you can incorporate some of that into what you are doing.
Dim postData As String = String.Format("RedirectLocation=RequestMethod=&username={0}&password={1}", _username, _password)
Dim _loginRequest As HttpWebRequest = WebRequest.Create(loginurl)
With _loginRequest
.Method = "POST"
.ContentLength = postData.Length
.ContentType = "application/x-www-form-urlencoded"
.KeepAlive = True
.AllowAutoRedirect = False
.CookieContainer = New CookieContainer
Using writer As New StreamWriter(.GetRequestStream)
writer.Write(postData)
End Using
.Timeout = tsTimeOut.TotalMilliseconds
_loginResponse = .GetResponse()
End With