I have this code to read JSON data from the parse.com
protected void Button4_Click(object sender, EventArgs e)
{
string URL = "https://api.parse.com/1/classes/SecondObject";
// string DATA = jsonString;
string text;
var request = WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "aa");
request.Headers.Add("X-Parse-REST-API-Key", "bb");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
//IEnumerable<parseo
}
unfortunately i get 400 bad request.
what i want is to read all the json that exist there is my class that called "secondobject".
can anyone help me to figure this issue ?
Thank you.
When you created your object, you got back a full url containing an identifier for your particular instance of SecondObject in the Location header. You need to access that full url.
For example, when you posted your object, you got back the following headers
Status: 201 Created
Location: https://api.parse.com/1/classes/SecondObject/E234jdnsl
Moreover, you also received the following json in the body:
{
"createdAt": [timestamp],
"objectId": "E234jdnsl"
}
That E234jdnsl bit is the object identifier of your particular instance. You then need to point your WebRequest to the url https://api.parse.com/1/classes/SecondObject/E234jdnsl to retrieve it.
As mentioned in the comments, your code is 99% correct. The only problem is you're using a POST command to retrieve data when you should use a GET command instead.
Here's some slightly updated code using a GET command that should work for you. I added some code at the end to read the stream into a StringBuilder and display it in a textbox but you can change that to whatever you need.
private void Button4_Click(object sender, EventArgs e)
{
string URL = "https://api.parse.com/1/classes/SecondObject";
var request = WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "YOUR_APP_ID");
request.Headers.Add("X-Parse-REST-API-Key", "YOUR_REST_API_KEY");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
StringBuilder sbTempData = new StringBuilder();
while (reader.Peek() > -1)
{
sbTempData.AppendLine(reader.ReadLine());
}
txtResults.Text = sbTempData.ToString();
}
Note that this will retrieve every object in that class. If you only want to retrieve certain objects in the class, then you can modify your url like https://api.parse.com/1/classes/ClassName/ObjectID
For more information see https://parse.com/docs/rest/guide#queries
I have solve the problem
string URL = "https://api.parse.com/1/classes/SecondObject";
// string DATA = jsonString;
string text;
var request = WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "aa");
request.Headers.Add("X-Parse-REST-API-Key", "bb");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
string strResponse = null;
if (!reader.EndOfStream)
{
strResponse = reader.ReadToEnd();
}
Now the strResponse contains all the data that exist in the "SecondObject".
Thank you
Related
I am new with web service and API's and trying to get a response from a URL with a post method and passing a parameter to it. I am developing a C# winform application that sending request to this api and must return the output in JSON format. Below is my code so war i only getting an OK response instead of the actual JSON data.
private void button1_Click(object sender, EventArgs e)
{
string postData = "station=sub";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Uri target = new Uri("http://apijsondata/tz_api/");
WebRequest myReq = WebRequest.Create(target);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = byteArray.Length;
using (var dataStream = myReq.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (var response = (HttpWebResponse)myReq.GetResponse())
{
//Do what you need to do with the response.
MessageBox.Show(response.ToString());
}
}
You should use a StreamReader together with HttpWebResponse.GetResponseStream()
For example,
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
I am currently working on implementing a class for accessing rest webservices with my C# program. I managed to do that for PUT, Post and GET, but I have problems with the Patch. The following error occurs everytime:
There is an exception error “System.Net.WebException” in System.ddll
Additional information: remote server reported: (400) Unvalid request
I have researched and tried out various things – to no avail. I would appreciate any help!
Many thanks in advance
public string WebserviceSenden()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create( GrundURL + ErweiterungsURL);
// Set the Method property of the request to POST.
request.Method = Methode;
// Create POST data and convert it to a byte array.
string postData = DateSenden;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
public string WebserviceEmpfangen()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create(
GrundURL + ErweiterungsURL);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
return responseFromServer;
}
}
private void button1_Click(object sender, EventArgs e)
{
String Jason = "";
RestClient AbfrageStarten = new RestClient();
AbfrageStarten.GrundURL = "URL";
AbfrageStarten.ErweiterungsURL = "540697";
Jason = AbfrageStarten.WebserviceEmpfangen();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<List<Lagereinheit>>(Jason, settings);
KorrekturLagereinheit = list[0];
KorrekturLagereinheit.stueckzahl = 5858;
string Test;
Test = JsonConvert.SerializeObject(KorrekturLagereinheit, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
RestClient AntwortSenden = new RestClient();
AntwortSenden.GrundURL = "URL";
AntwortSenden.ErweiterungsURL = "540697";
AntwortSenden.Methode = "Patch";
AntwortSenden.DateSenden = Test;
AntwortSenden.WebserviceSenden();
}
Error message
Many thanks in advance
I've always done my web services in PHP. Now I'm trying some ASP.NET on a project and I found myself on a tricky situation. I have the following C# code, behaving as a "client"
public void sendRequest(string URL, string JSON)
{
ASCIIEncoding Encode = new ASCIIEncoding();
byte[] data = Encode.GetBytes(JSON);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
returnRequestTxtBx.Text = responseText;
}
Well, now I want to handle on the ASPX.CS side...
my question is... how do I access the data I sent as a POST?
Is there a way in the "Page_Load" method that I can handle the JSON I sent?
To read post method data on your server side read HttpContext.Request.Form method:
protected void Page_Load(object sender, EventArgs e)
{
string value=Request.Form["keyName"];
}
Or if you want to access row body data simply read: Request.InputStream.
And if you want handle Json format consider Newtonsoft.Json packege.
All I want is to send xml data from C# desktop application to ASP.Net webpage.
My C# code look like this.
public string SendRequest()
{ string data = "<?xml version="1.0"?><author>Gambardella, Matthew</author>";
string _result;
Uri uri = new Uri("http://localhost:62511/Default");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var streamResponse = response.GetResponseStream();
var streamRead = new StreamReader(streamResponse);
Console.Write(response.StatusCode);
_result = streamRead.ReadToEnd().Trim();
streamRead.Close();
streamResponse.Close();
response.Close();
return _result;
}
My ASP .Net Code looks like this
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(Request.InputStream))
{
string xml = reader.ReadToEnd();
labelsam.Text = xml;
}
....
}
labelsam is a label on web page.But I get nothin in labelsam.Is there anyway to check whether the data is received.Also whats wrong with code?
You have to specify content length for post method.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength=data.Length; //ugly, but at least so
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
In a C# Windows Forms application I can get the contents of a webpage using:
string content = webClient.DownloadString(url);
And I can get the HTTP header using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
string response = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();
Is there a way to get both the contents and the HTTP status code (if it fails) in one trip to the server instead of twice?
Thanks.
You can read the data from the Stream inside the HttpWebResponse object:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;
string contents = reader.ReadToEnd();
}
In this way you will have to detect the encoding by hand, or using a library to detect encoding. You can read the encoding as a string from the HttpWebResponse object as well, when one exists, it is inside the ContentType property. If the page is Html, then you will have to parse it for a possible encoding change in the top of the document or inside the head.
Read handling the encoding from ContentType header
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
string content;
HttpStatusCode statusCode;
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var contentType = response.ContentType;
Encoding encoding = null;
if (contentType != null)
{
var match = Regex.Match(contentType, #"(?<=charset\=).*");
if (match.Success)
encoding = Encoding.GetEncoding(match.ToString());
}
encoding = encoding ?? Encoding.UTF8;
statusCode = ((HttpWebResponse)response).StatusCode;
using (var reader = new StreamReader(stream, encoding))
content = reader.ReadToEnd();
}
WebClient
I assume you use WebClient because its easy webrequest-to-string handling. Unfortunately, WebClient does not expose the HTTP response code. You can either assume the response was positive (2xx) unless you get an exception and read it:
try
{
string content = webClient.DownloadString(url);
}
catch (WebException e)
{
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
var statusCode = response.StatusCode;
}
Or if you're really interested in the success code you can use reflection as explained here.
HttpClient
You can also use HttpClient if you're on .NET 4.5, which does expose the response code, as explained here:
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
var statusCode = response.StatusCode;
}
HttpWebRequest
Alternatively, you can just use HttpWebRequest to get the status and response as explained here:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
var statusCode = response.StatusCode;
}
I think, you have not realised, that in the second case you have access to the content as well (although it takes a little more effort to get as a string).
Look at the Microsoft documentation: http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream(v=vs.110).aspx which shows you how to ge a response stream from the web response, and then how to get the string data from that stream.
And I can get the HTTP header using:
request.Method = "GET";
Method GET returns HEAD and BODY sections in response.
HTTP also support a method HEAD - which returns HEAD section only.
You can get BODY from HttpWebResponse using GetResponseStream method.