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();
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 trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}
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
I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}