here is the function:
private void button6_Click(object sender, EventArgs e1)
{
string requestText = string.Format("strXMLData={0}", System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e));
string data = "strXMLData=%3c&strXMLFileName=text1.xml"; //Working I am //getting in service mathod <
string data = "strXMLData=%3e&strXMLFileName=text1.xml"; //Working I am getting in service mathod >
//string data = "strXMLData=%3c%3e&strXMLFileName=text1.xml"; //this is also working,I am getting in service mathod
//string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "multipart/form-data";
request.ContentLength = dataStream.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
var reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream());
string dataReturn = reader.ReadToEnd();
}
in above code I have written 3 cases from which two are working and 3rd case
string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
is not working can you explain why it is not passing xml string, I am trying to pass
<tag1>
value
</tag1>
As we cannot pass xml without encoding so I encoded this string using
string requestText = string.Format( System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e)); //which returns %3ctag1%3etext%3c%2ftag1%3e
can you explain how to pass xml string..?
without getting error 500
here is web service method
[WebMethod]
public string ReceiveXMLByContent(string strXMLData, string strXMLFileName)
{
string b = System.Web.HttpUtility.UrlDecode(strXMLData);
return "worked";
}
The problem always lies in the following lines
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "multipart/form-data";
Make sure the request.ContentType is especially proper, like in this syntax:
request.ContentType = "text/xml; charset=\"utf-8\"; action=\"HeaderName\";";
Make sure you use try and catch method like this:
private void button6_Click(object sender, EventArgs e1)
{
string GetHttpPost = string.Empty;
GetHttpPost = CallHTTPPostMethod();
}
public string CallHTTPPostMethod()
{
try
{
//Your code
return YourResponseXMLInStringFormat;
}
catch(Exception wex)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return pageContent;
}
}
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 want to convert the Object received in the function and do as needed to convert it to an object ({"some_key": "some_value"}).
Here is my code:
public HttpRequests(string url, string method, Object data)
{
//The following prepares data, according to received parameter
if (data is Array)
{
data = (Array)data;
}
else if (data is Dictionary<Object, Object>)
{
data = ((Dictionary<string, string>)data)["something"] = platform_secret;
data = ((Dictionary<string, string>)data)["something2"] = "1";
}
method = method.ToUpper(); //POST or GET
this.url = just_url + url;
this.data = Newtonsoft.Json.JsonConvert.SerializeObject(data);
this.method = method;
}
public Object performRequest()
{
if (this.data != null && url != null)
{
WebRequest request = HttpWebRequest.Create(url);
byte[] data_bytes = Encoding.ASCII.GetBytes(Convert.ToChar(data)[]);
//^ this does not work. Am I supposed to do this?
// as I said, what I want is to get an object {key: something} that can be read
// by $_POST["key"] in the server
request.Method = method;
request.ContentType = "application/x-www-form-urlencoded"; //TODO: check
//request.ContentLength = ((Dictionary<string, string>) data);
request.ContentLength = data_bytes.Length;
Stream dataStream = request.GetRequestStream(); //TODO: not async at the moment
//{BEGIN DOUBT
dataStream.Write(data_bytes, 0, data_bytes.Length);
dataStream.Close();
//DOUBT: DO THIS ^ or THIS:_ ???
StreamWriter writer = new StreamWriter(dataStream);
writer.Write(this.data);
//End DOUBT}
WebResponse response = request.GetResponse();
Stream dataResponse = response.GetResponseStream();
writer.Close();
response.Close();
dataStream.Close();
return dataResponse.
}
What exactly am I missing here?
As you initially assign this.data = Newtonsoft.Json.JsonConvert.SerializeObject(data);, suppose his.data has type string (you can change if it is otherwise).
Then instead of byte[] data_bytes = Encoding.ASCII.GetBytes(Convert.ToChar(data)[]); you need to write just byte[] data_bytes = Encoding.ASCII.GetBytes(data);
After use this
//{BEGIN DOUBT
dataStream.Write(data_bytes, 0, data_bytes.Length);
dataStream.Close();
It will help to do the call with some data but it does not help to solve your problem. request.ContentType = "application/x-www-form-urlencoded"; does not expect that the data is Newtonsoft.Json.JsonConvert.SerializeObject serialized. It expects a string containing & separated pairs that are urlencoded.
name1=value1&name2=value2&name3=value3
So, you need to use this format instead of JSON.
You need to use the first piece of code. Here is and exmaple.
But the second piece could work too, I guess. You have missed nothing on C# side. A problem could be in the data you are going to transfer, however. If it is not correctly encoded, for example.
You should be doing something closer to the lines of this...
void Main()
{
var formSerializer = new FormEncodedSerializer();
formSerializer.Add("key", "value");
formSerializer.Add("foo", "rnd");
formSerializer.Add("bar", "random");
var uri = #"http://example.com";
var contentType = #"application/x-www-form-urlencoded";
var postData = formSerializer.Serialize();
var http = new Http();
Console.WriteLine (http.Post(uri, postData, contentType));
}
public class Http
{
public string Post(string url, string data, string format)
{
var content = Encoding.UTF8.GetBytes(data);
var contentLength = content.Length;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentType = format;
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(content, 0, content.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}`
public class FormEncodedSerializer
{
private Dictionary<string, string> formKeysPairs;
public FormEncodedSerializer(): this(new Dictionary<string, string>())
{
}
public FormEncodedSerializer(Dictionary<string, string> kvp)
{
this.formKeysPairs = kvp;
}
public void Add(string key, string value)
{
formKeysPairs.Add(key, value);
}
public string Serialize()
{
return string.Join("", this.formKeysPairs.Select(f => string.Format("&{0}={1}", f.Key,f.Value))).Substring(1);
}
public void Clear()
{
this.formKeysPairs.Clear();
}
}
I did not really understand what your service expects, in which format you have to send the data.
Anyway, if you set ContentType like "application/x-www-form-urlencoded", you must encode your data with this format. You can simply do it with this code;
var values = ((Dictionary<string, string>)data).Aggregate(
new NameValueCollection(),
(seed, current) =>
{
seed.Add(current.Key, current.Value);
return seed;
});
So, your data is sent like "something=platform_secret&something2=1"
Now, you can send form data simply:
WebClient client = new WebClient();
var result = client.UploadValues(url, values);
I think your first function with signature public HttpRequests(string url, string method, Object data) dosn't seem have any logical error but in your second function with signature public Object performRequest() you have some issue:
if your HTTP method is GET you don't need to write content stream.
if your method is POST and your data are JSON you need setting up HTTP requester like this:
request.ContentType = "application/json";
and finally, flush your stream before you close it, like this request.Flush();
I am trying to post data from PCL project to remote server. Below is my code:
public async Task<bool> SendToken(string deviceToken, string userId)
{
HttpWebRequest request;
string url = "http://192.168.1.171:91/api/updatePushDeviceToken";
request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.Method = "POST";
string postData = string.Format("userId={0};token={1}&deviceType={2}", userId, deviceToken, deviceType);
var data = Encoding.UTF8.GetBytes(postData);
try
{
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}
catch (Exception e)
{
string m = e.Message;
}
return false;
}
private void FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
var responseString = readStream.ReadToEnd();
}
While running above code, below exception was thrown:
System.Net.WebException: The remote server returned an error: (411)
Length Required.
PCL doesn't contain ContentLength property, hence I added Length as below but now I am getting exception as:
try
{
request.Headers[HttpRequestHeader.ContentLength] = "0";
}
catch (Exception e)
{
}
System.ArgumentException: This header must be modified with the
appropiate property. at
System.Net.WebHeaderCollection.CheckRestrictedHeader (System.String
headerName)
Your request is missing of ContentLength property of your post parameters.
var parameters = Encoding.ASCII.GetBytes(qstring);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContentType="application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentLength = parameters.Length;
//Send it
var reqStream = request.GetRequestStream();
reqStream.Write(parameters, 0, parameters.Length);
reqStream.Close();
//read it
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string responseHtml = sr.ReadToEnd().Trim();
And please use querystring format to post data, for example : "userId={0}&token={1}&..."
I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.
I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.