I am trying to create a HTTP Post that returns a JSON object with 2 attributes.
Details are below:
HTTP POST to http://text-processing.com/api/sentiment/ with form encoded data which contains a string. A JSON object response with 2 attributes is retuned; lable and negative.
I am tying to do this in c#, which is where I am struggling.
Thank you
You can try using a WebClient like this
WebClient webclient = new WebClient();
NameValueCollection postValues = new NameValueCollection();
postValues.Add("foo", "fooValue");
postValues.Add("bar", "barValue");
byte[] responseArray = webclient.UploadValues(*url*, postValues);
string returnValue = Encoding.ASCII.GetString(responseArray);
MSDN page also has an example.
Related
I'm using a WebClient to make a POST request with a query string but I can't see the raw string. This is what I have:
WebClient TheWebClient = new WebClient();
TheWebClient.QueryString.Add("Param1", "1234");
TheWebClient.QueryString.Add("Param2", "4567");
TheWebClient.QueryString.Add("Param3", "4539");
var TheResponse = TheWebClient.UploadValues("https://www.example.com/posturl", "POST", TheWebClient.QueryString);
string TheResponseString = TheWebClient.Encoding.GetString(TheResponse);
//problem is that this only shows the keys
var RawQueryString = TheWebClient.QueryString;
How can I see the actual raw query string?
WebClient.UploadValues doesn't save the request "raw query string" simply because you provided it with them, and it's not gonna change, thus is redundant.
Furthermore, HttpPost requests doesn't use query string for the request payload, it has a url, a message payload; which is appended after the headers, maybe query string. Thus there is nothing new the client class should let you know, so it won't save it.
I want to send via POST request two parameters to a Web API service. I am currently receiving 404 not found when I try in the following way, as from msdn:
public static void PostString (string address)
{
string data = "param1 = 5 param2 = " + json;
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address, method, data);
Console.WriteLine (reply);
}
where json is a json representation of an object. This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned.
Can somebody provide me an example of WebClient which sends two parameters to a POST request?
Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here)
I would suggest sending your parameters as a NameValueCollection.
Your code would look something like this when sending the parameters with a NameValueCollection:
using(WebClient client = new WebClient())
{
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param1", "5");
requestParameters.Add("param2", json);
byte[] response = client.UploadValues("your url here", requestParameters);
string responseBody = Encoding.UTF8.GetString(response);
}
Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters.
I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data:
public static void PostString (string address)
{
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address + param1, method, json);
Console.WriteLine (reply);
}
Where address needs to expect the value parameter.
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(url, "sign=fsadfasdf&charset=utf-8");
}
Server can get value of sign and charset.
But there is a third parameter LIST, which is a list of object (this object is an entity class).
How can I pass this parameter to the server?
I tried to use "sign=fsadfasdf&charset=hhh&list=" + Json(list) as postData (convert List to json string). But the server didn't get value of this list param.
I hate to post 1 line answers with links in them but this has been solved on here before ...
POSTing JsonObject With HttpClient From Web API
HttpClient class is designed to solve exactly this problem, i believe its found in the nuget package "Microsoft.AspNet.WebApi.Client", this should add the namespace "System.Net.Http" to your project.
It's also geared at being completely async which should be nicer to your server!
EDIT:
To post an array / collection you would do something like this ...
var myObject = (dynamic)new JsonObject();
myObject.List = new List<T>();
// add items to your list
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
I have a handler. When I call it with URL that is to say GET method, it works because I get values with my below handler code.
var encodedUrl = HttpUtility.UrlEncode(context.Request.QueryString.ToString());
How can I get values when I use post method which is below from Handler side:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["a"] = "a";
data["b"] = "b";
var response = wb.UploadValues("http://localhost:126/Web", "POST", data);
}
When you receive an http response you basically depend on the "Content Type". Depending on this type is that you read it.
Here is a reference on this topic:
http://msdn.microsoft.com/en-us/library/ms525208(v=vs.90).aspx
For instance if you decide to receive an "application/json" response type. You may be able to use this:
Using WebClient for JSON Serialization?
From I can see in your sample it looks like you are trying to implement an "application/x-www-form-urlencoded" and the post needs to be formatted accordingly. Here is a sample for that:
http://msdn.microsoft.com/en-us/library/system.net.webclient.headers(v=vs.110).aspx
How are parameters sent in an HTTP POST request?
But there are other options available. I hope this is the answer you were looking for.
I'm having this strange problem when i try to access elements in json from javascript. i retreve a json string from a url like so,
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"www.someurl.com");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
sjson = client.DownloadString(#"www.someurl.com");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = Int32.MaxValue;
sjson = oSerializer.Serialize(sjson);
But when i access this sjson variable from javascript in html code, it doesn't return anything, but if i hard code it, it returns the values, please help on this one. I tried many things but didn't work. I also tried to just pass the retreieved json string without serializing, when i do that the javascript stops working. :( following is the javascript code,
<script type="text/javascript">
var jsons = JSON.parse('<%=sjson%>');
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
The issue is
document.writeln(myobject.Body[0].RowId.SensorIdValue);
returns a value if i use the myobject variable, but
document.writeln(jsons.Body[0].RowId.SensorIdValue);
returns nothing when i use it with the parsed value. :(
following is the sample of the json output (response.write) i get after running the serializer via c#,
Please help me on this one..i cant seem to find the problem here.
EDIT:
if it help, the fiollowing is the json string i get straight from the server witout making any serializations,
Few contents of the question have been removed due to owner request
What you're seeing there is doubly JSON-serialized data. You retrieved JSON from the remote server and then JSON encoded it a second time with JavaScriptSerializer. This is a post I wrote about that, in the context of ASMX ScriptServices, which explains in more detail: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/. Your case isn't exactly the same, but the end result is.
Remove the JavaScriptSerializer code and return the JSON string you retrieved (sjson) instead of serializing it a second time.
You don't need to use a Json serializer because the remote server already returns a JSON encoded string that you could directly use in your page and avoid the double encoding.
So:
public string GetJson()
{
// Create Client
using (WebClient client = new WebClient())
{
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
return client.DownloadString(
#"www.someurl.com"
);
}
}
and then:
<script type="text/javascript">
var jsons = <%= GetJson() %>;
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>