I am trying to send dictionary using POST in C# to a django server.
The server receives the request and acknowledges with 200 message, however it receives an empty Multi Value Dictionary.
Here is the client sending POST request.
public class Hello1
{
public static void Main()
{
Console.WriteLine("Request Initiating");
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["key1"] = "test";
data["key2"] = "TEST2";
data["key3"] = "NA";
string url = "http://10.34.150.153:8000/key_detect/detect/";
var response = wb.UploadValues(url, "POST", data);
string result = System.Text.Encoding.UTF8.GetString(response);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
See this post:
POSTing JSON to URL via WebClient in C#
You need to serialize your data to JSON before you upload it.
var data = new NameValueCollection();
data["key1"] = "test";
data["key2"] = "TEST2";
data["key3"] = "NA";
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(data);
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
Related
I have an API using POST Method.From this API I can download the file via Postmen tool.But I would like to know how to download file from C# Code.I have tried below code but POST Method is not allowed to download the file.
Code:-
using (var client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
TransId Id = new TransId()
{
id = TblHeader.Rows[0]["id"].ToString()
};
List<string> ids = new List<string>();
ids.Add(TblHeader.Rows[0]["id"].ToString());
string DATA = JsonConvert.SerializeObject(ids, Newtonsoft.Json.Formatting.Indented);
string res = client.UploadString(url, "POST",DATA);
client.DownloadFile(url, ConfigurationManager.AppSettings["InvoicePath"].ToString() + CboGatePassNo.EditValue.ToString().Replace("/", "-") + ".pdf");
}
Postmen Tool:-
URL : https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed
Header :-
Content-Type : application/json
X-Cleartax-Auth-Token :b1f57327-96db-4829-97cf-2f3a59a3a548
Body :-
[
"GLD24449"
]
using (WebClient client = new WebClient())
{
client.Headers.Add("X-Cleartax-Auth-Token", ConfigurationManager.AppSettings["auth-token"]);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string url = ConfigurationManager.AppSettings["host"] + ConfigurationManager.AppSettings["taxable_entities"] + "/ewaybill/download?print_type=detailed";
client.Encoding = Encoding.UTF8;
//var data = "[\"GLD24449\"]";
var data = UTF8Encoding.UTF8.GetBytes(TblHeader.Rows[0]["id"].ToString());
byte[] r = client.UploadData(url, data);
using (var stream = System.IO.File.Create("FilePath"))
{
stream.Write(r,0,r.length);
}
}
Try this. Remember to change the filepath. Since the data you posted is not valid
json. So, I decide to post data this way.
I think it's straight forward, but instead of using WebClient, you can use HttpClient, it's better.
here is the answer HTTP client for downloading -> Download file with WebClient or HttpClient?
comparison between the HTTP client and web client-> Deciding between HttpClient and WebClient
Example Using WebClient
public static void Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
client.Encoding = Encoding.UTF8;
var data = UTF8Encoding.UTF8.GetBytes("[\"GLD24449\"]");
byte[] r = client.UploadData(uri, data);
using (var stream = System.IO.File.Create(path))
{
stream.Write(r, 0, r.Length);
}
}
Here is the sample code, don't forget to change the path.
public class Program
{
public static async Task Main(string[] args)
{
string path = #"download.pdf";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
var uri = new Uri("https://ewbbackend-preprodpub-http.internal.cleartax.co/gst/v0.1/taxable_entities/1c74ddd2-6383-4f4b-a7a5-007ddd08f9ea/ewaybill/download?print_type=detailed");
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = new StringContent("[\"GLD24449\"]", Encoding.UTF8, "application/json")
};
request.Headers.Add("X-Cleartax-Auth-Token", "b1f57327-96db-4829-97cf-2f3a59a3a548");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using (FileStream fs = File.Create(path))
{
await response.Content.CopyToAsync(fs);
}
}
else
{
}
}
I have call to REST service from jscript that works fine:
post('/MySite/myFunct', { ID:22 })
How to make this call from C# in most native c# way?
UPD:
I need HTTPS solution also.
UPD:
And I need to use cookies
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "ID", "22" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com", content);
var responseString = await response.Content.ReadAsStringAsync();
Old traditional way is using HttpClient / HttpWebRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(model);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Apart from this I prefer more Restclient /Restsharp from nuget.
A simple example of post request will be like this
using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
var request = new RestRequest();
request.BaseUrl = "http://carma.org";
request.Action = "api/1.1/searchPlants";
request.AddParameter("location", 4338);
request.AddParameter("limit", 10);
request.AddParameter("color", "red");
request.AddParameter("format", "xml");
request.ResponseFormat = ResponseFormat.Xml;
var plants = client.Execute<PowerPlantsDTO>(request);
MessageBox.Show(plants.Count.ToString());
}
You can use HTTP Verbs directly from call
A Post example:
public void Create(Product product)
{
var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
request.AddJsonBody(product);
client.Execute(request);
}
A Delete Example
public void Delete(int id)
{
var request = new RestRequest("Products/" + id, Method.DELETE);
client.Execute(request);
}
For adding header in request
request.AddHeader("data", "test");
A Get Request
private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);
RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;
I'm receiving a 400 Bad Request error message when posting a pin on Pinterest. It works using Postman, but doesn't work programmatically. Using C#, has anyone been able to successfully post a pin on Pinterest without using the pinsharp wrapper?
private void postPinterest(string messages, string id, string usertoken, string image, string boardname, string username)
{
string link = null;
boardname = boardname.Replace(" ", "-");
string board = username + "/" + boardname;
string url = "https://api.pinterest.com/v1/pins?access_token=" + usertoken;
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(board))
sb.Append("&board=" + HttpUtility.UrlEncode(board));
if (!string.IsNullOrEmpty(messages))
sb.Append("¬e=" + HttpUtility.UrlEncode(messages));
if (!string.IsNullOrEmpty(link))
sb.Append("&image_url=" + HttpUtility.UrlEncode(link));
string postdata = sb.ToString().Substring(1);
PostData(url, postdata);
}
private object PostData(string url, string postdata)
{
object json=null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.Accept = "application/json";
using (var stream = req.GetRequestStream())
{
byte[] bindata = Encoding.ASCII.GetBytes(postdata);
stream.Write(bindata, 0, bindata.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string response = new StreamReader(resp.GetResponseStream()).ReadToEnd();
json = JsonConvert.DeserializeObject<dynamic>(response);
return json;
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
return json;
}
}
}
}
return json;
}
EDIT:
It doesn't work using the JSON format or x-www-form-urlencoded format.
I changed the content type to application/x-www-form-urlencoded and now I'm receiving the error message below. I receive 400 Bad Request error using JSON format:
"{\n \"message\": \"405: Method Not Allowed\",\n \"type\": \"http\"\n}"
The problem is the the parameter that you are posting.
In the Api i could find board as a parameter but both note and image comes under field parameter which specifies the return type JSON.
As per documentation on this page you can post in this format
https://api.pinterest.com/v1/boards/anapinskywalker/wanderlust/pins/?
access_token=abcde&
limit=2&
fields=id,link,counts,note
So I tried the following and its getting response
https://api.pinterest.com/v1/boards/?access_token="YourTokenWithoutQuotes"&fields=id%2Ccreator
Would suggest you to first test the Api you are hitting putting a breakpoint inside the PostData function and check if the passed url is in the correct format and compare it with Pininterest API Explorer.
As you might have already received authorization code and access token so I am assuming your post function should be working fine.
public string postPinterest(string access_token,string boardname,string note,string image_url)
{
public string pinSharesEndPoint = "https://api.pinterest.com/v1/pins/?access_token={0}";
var requestUrl = String.Format(pinSharesEndPoint, accessToken);
var message = new
{
board = boardname,
note = note,
image_url = image_url
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response;
}
I have some code:
public Task<IRestResponse> SendRequest(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse>();
client.ExecuteAsync(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
response contains all but not the answer from url (response doesnt' contain Data object). When I specify object for ExecuteAsync:
public Task<IRestResponse<MyClass>> SendRequest(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse<MyClass>>();
client.ExecuteAsync<MyClass>(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
public class MyClass
{
public bool ResultCheck { get; set; }
public string Message { get; set; }
}
in response I can find object Data (response.Data) which contains fields with values from url.
For example I receive response with Data: { ResultCheck=true, Message="Result!" }
How can I receive filled Data from url with any object without specifiing type - MyClass. I wan't to receive response with any number of fields for different urls. I want to receive some anonymous object.
One way would be to use Generics and dynamic objects. This should allow you to specify any object type to be converted to a response.
You can therefore change the method to
public Task<IRestResponse<T>> SendRequest<T>(string url, string bodyJson)
{
var client = new RestClient(url);
var request = new RestRequest
{
RequestFormat = DataFormat.Json;
Method = Method.POST;
};
request.AddBody(bodyJson);
var taskCompletionSource = new TaskCompletionSource<IRestResponse<T>>();
client.ExecuteAsync<T>(request, response =>
{
taskCompletionSource.SetResult(response);
});
return taskCompletionSource.Task;
}
Then we can create temp object using dynamic. We can then fill this will all the information we need
// Create temp obj
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
finally at the call site we state the type is dynamic. Hopefully the rest api can forward this onto the client and they can retrieve the object as type dynamic.
SendRequest<dynamic>(url, JsonConvert.SerialiseObject(employee));
The client can then do something like
dynamic response = GetResponse(...);
var name = response.Name;
I have 2 c# asp.net projects. 1 is an api. 1 is consuming this api.
My api:
public class MyApiController : ApiController
{
public dynamic ValidateToken(string token)
{
return myValidationMethod(token);
}
}
Consuming my api from another project:
public class MyController : Controller
{
[HttpPost]
public ActionResult ValidateToken(string token)
{
var url = "http://localhost:1234/myapi/validatetoken";
var parameters = "token=" + token;
using (var client = new WebClient())
{
var result = client.UploadString(url, parameters);
return Json(result);
}
}
}
In project 2 where I consume the api, client.UploadString throws a System.Net.WebException - The remote server returned an error: (404) Not Found.
When I test the api with the chrome rest client it works with http://localhost:1234/myapi/validatetoken?token=myToken
Why can WebClient not find it?
Solved
I got this to work thanks to #BrentMannering with a small change to add content length:
var url = "http://localhost:1234/myapi/validatetoken?token=" + token;
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = 0; //got an error without this line
var response = request.GetResponse();
var data = response.GetResponseStream();
string result;
using (var sr = new StreamReader(data))
{
result = sr.ReadToEnd();
}
return Json(result);
I don't think UploadString is sending the data as params, so the routing engine on the API side cannot map to an action, hence the 404. According to the MSDN documentation the method is encoding to a Byte[] prior to uploading, this could be part of the problem.
Try using the UploadValues method
var url = "http://localhost:1234/myapi/validatetoken";
var nv = new NameValueCollection { { "token", token } };
using (var client = new WebClient())
{
var result = client.UploadValues(url, nv);
return Json(result);
}
Otherwise to mimic the test you are doing with the chrome client use WebRequest
var url = "http://localhost:1234/myapi/validatetoken?token=" + token;
var request = WebRequest.Create(url);
request.Method = "POST";
var data = request.GetResponse().GetResponseStream();
string result = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
result = sr.ReadToEnd();
}
return Json(result);
WebClient.UploadString method sends an Http POST method. Did you try to access your APIController with a POST method from the test client ? I am assuming your test client sent a GET request and it worked.
There is a different overload where you can mention the Action method type.
var url = "http://localhost:1234/myapi/validatetoken";
var parameters = "token=" + token;
string method = "GET"; //or POST as needed
using (var client = new WebClient())
{
var result = client.UploadString(url,method , parameters);
return Json(result);
}