i have used following code in my c# application
string verification_url = #"http://site.com/posttest.php?";
string verification_data = "test=524001A";
string result = string.Empty;
result = Post(verification_url, verification_data);
public string Post(string url, string data)
{
string result = "";
try
{
byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(#url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
result = _Answer.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (result.Length < 0)
result = "";
return result;
}
Server side PHP code
<?php
$test=$_REQUEST['test'];
echo $test;
?>
post method always returns empty value
please help me
try
<?php
print_r($_REQUEST);
?>
to show the raw REQUEST vars. im not sure where you setting test in your c# code.
You need to add the verification data as parameter to the request url eg.
string verification_data = "test=524001A";
string verification_url = #"http://site.com/posttest.php?" + verification_data;
That way your actual request URL would be:
http://site.com/posttest.php?test=524001A
Could you try not closing the RequestStream? Try removing the following line:
PostData.Close();
PS: Do you have the necessary .net permissions to do this?
i have changed the following line
string verification_url = #"http://site.com/posttest.php?";
to
string verification_url = #"http://www.site.com/posttest.php?";
it now works fine
Related
When I post to server using HttpWebRequest and method POST, the NameValueCollection in the asp code has no values. I have identical code working with other server pages, the only difference is the string data posted is a bit different.
code that posts is from a c# desktop application:
string responseFromServer = string.Empty;
System.Net.HttpWebRequest request = null;
System.IO.StreamReader reader = null;
System.Net.HttpWebResponse response = null;
string http = string.Empty;
http = "http://www.apageonmywebsite.aspx";
request = HttpWebRequest.Create(http) as HttpWebRequest;
request.Method = "POST";
UTF8Encoding encoding = new UTF8Encoding();
//send a namevalue pair -that is what the website expects via the request object
string postData = "TRIALID=" + System.Web.HttpUtility.UrlEncode(trialUserID, encoding);
byte[] byte1 = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byte1.Length;
request.Timeout = 20000;
System.IO.Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
System.Threading.Thread.Sleep(1000);
response = (HttpWebResponse)request.GetResponse();
System.IO.Stream dataStream = response.GetResponseStream();
reader = new System.IO.StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
if (responseFromServer.Contains("\r"))
{
responseFromServer = responseFromServer.Substring(0, responseFromServer.IndexOf("\r"));
}
Server code:
NameValueCollection postedValues = Request.Form; // Request.Form worked locally, failed on server(count=0)
IEnumerator myEnumerator = postedValues.GetEnumerator();
try
{
foreach (string s in postedValues.AllKeys)
{
if (s == "TRIALID")
{
regcode += postedValues[s];
break;
}
}
}
catch (Exception ex)
{
Response.Clear();
Response.Write("FAILED");
this.resultMsg = "FAILED. Exception: " + ex.Message;
LogResult();
return;
}
if (string.IsNullOrEmpty(regcode))
{
Response.Write("postedvalues count=" + postedValues.Count.ToString() + ": no regcode:");
this.resultMsg ="postedvalues count=" + postedValues.Count.ToString() + ": no regcode:";
LogResult();
return;
}
In the sending application, responseFromServer is postedvalues count=0:no regcode:
So the data is posted but not "seen" on the server.
The trialUserID field used in the urlencode method is a string containing user domain name plus user name from the Environment object plus the machine name.
Answer to my own question is that the url needs to be https not http.
I converted my asp.net website to https one year ago and when I created the app that sends the posted data I assumed that since the entire website is configured to automatically redirect to https that should take care of it. Clearly, the webrequest needs the https hardcoded in the url.
Just tried to click the Accept button but that is not allowed for two days since I answered my own question.
I'm trying to send some string from a service to a webmethod service with the following code:
private void SendRequest(string filePath, string webService)
{
try
{
using (var wb = new WebClient())
{
string data = File.ReadAllText(filePath);
data = "data=" + data;
string res = wb.UploadString(webService, data);
}
}
catch (Exception e)
{
logEvents.Write(MyLogClass.LogLevel.Info, "Data not sent " + e.Message);
}
}
For some reason I don't know res is returning the html code of the frontpage.
I was doing this previously with node and my webservice would accept the string without a problem and return 200.
The code of the web service starts as follows:
[WebMethod]
public static string Data(string data)
I've tried formatting the data in several ways and changing the arguments and the URLs are well. The problem is not in the web service since it works fine with my node request. What could it be?
Solved this by serializing the data being sent and using WebRequest instead of WebClient.
Edit
var webRequest = WebRequest.Create(webService);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
string data = File.ReadAllText(filePath);
var jsonObject = new { data };
var serializedObject = JsonConvert.SerializeObject(jsonObject);
var bytes = Encoding.ASCII.GetBytes(serializedObject);
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Try specifying Headers explicitly.
using (var wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string data = File.ReadAllText(filePath);
data = "data=" + data;
string res = wb.UploadString(webService, /*"POST",*/ data);
}
I am trying to convert voice to text using Google Speech API. I have a sample code below. It was working fine, it stopped working suddenly and now it always throws the error - 400 bad request. I am using GOOGLE_SPEECH_KEY for authentication without OAuth2 token.
Not sure what exactly I'm missing. Do I need to create OAuth authentication or do I need to modify any console settings in google portal or need to modify the code itself ? Please help!
I used all the below api's and same 400 error:
1. url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
2. url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
3. url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
public static string GoogleSpeechToTextApi(string flacUrl)
{
string pTranscriptText = "None", pTranscriptConfidence = "";
string appendText = "";
try
{
// Stream responseStream = imageResponse.GetResponseStream();
if (flacUrl != null)
{
string blobURI = flacUrl;
WebClient myWebClient = new WebClient();
Stream fileStream = myWebClient.OpenRead(blobURI);
byte[] BA_AudioFile = null;
using (var stream2 = new MemoryStream())
{
fileStream.CopyTo(stream2);
stream2.SetLength(stream2.Length);
stream2.Read(stream2.GetBuffer(), 0, (int)stream2.Length);
BA_AudioFile = stream2.GetBuffer();
}
string audioInput = Convert.ToBase64String(BA_AudioFile);
Config config = new Config();
config.encoding = "flac";
config.languageCode = "en";
config.sampleRate = "8000";
Audio audio = new Audio();
audio.content = audioInput;
JsonRequest request = new JsonRequest();
request.config = config;
request.audio = audio;
string json = JsonConvert.SerializeObject(request);
string url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // original api url
//url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
//url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
WebRequest webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
RootObject ro = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
dynamic JsonArray = JsonConvert.DeserializeObject(responseFromServer);
var jsonResult = JsonArray["results"];
foreach (var item in jsonResult)
{
appendText += item.alternatives[0].transcript;
}
}
return appendText;
}
catch (Exception ex)
{
return appendText = "Error";
}
}
}
}
Error 400 means that your request is not correct. You can try encoding = linear16, audioChannelCount = 2 and sampleRateHertz = 16000 with file wav.
Btw, you can pass your key in header request instead in your url
So I have this code in C#.
private void SendMessage()
{
// this is what we are sending
string post_data = "loginIdPost=" + 2 + "&" + "contentPost=" + absenceInputField.text;
string uri = "<URI IS HERE>";
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(new StreamReader(response.GetResponseStream()).ReadToEnd());
Debug.Log(response.StatusCode);
Console.WriteLine(response.StatusCode);
}
It sends some information to a PHP file, which then puts data into my database. The data is being successfully sent, but the HttpWebResponse is coming back blank. It returns "", an empty string.
This is my PHP code.
<?php
//Id
if (isset($_POST["loginIdPost"]))
{
$loginId = $_POST["loginIdPost"];
}
else
{
$loginId = null;
}
//Content
if (isset($_POST["contentPost"]))
{
$content = $_POST["contentPost"];
}
else
{
$content = null;
}
try
{
$conn = new PDO("Connection String");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
print("Error connecting to SQL Server.");
die(print_r($e));
}
$sth = $conn->prepare('Sql Query is here');
$sth->execute('details of execution are here');
echo "Success";
//Check Connection
if(!$conn)
{
die("Connection Failed. ". mysqli_connect_error());
}
?>
Does anyone know why I'm getting an empty string back, when I'd expect to be getting "Success" back. Again, no errors in the php code as the SQL query does insert data into my database.
I managed to fix it by just removing Console.Writeline.
I am running a server with a mysql database on it.
I am now making a C# program which has to put some data into the database.
For security reasons I would send the data to a php script which inserts the data in the local mysql database.
I am trying the code below, but when I use fiddler to check if the url is called, it doesn't show up, so it seems as if the url is never called.
My code looks like this:
string result = string.Empty;
string data2 = string.Empty;
string[] postdata = new string[8];
postdata[0] = "Date";
postdata[1] = log.EndTime.ToString();
postdata[2] = "Name";
postdata[3] = log.OwnerTask.Schedule.Name;
postdata[4] = "Status";
postdata[5] = log.ParsedStatus;
postdata[6] = "Message";
postdata[7] = log.ParsedMessage;
string Url = "http://x.x.x.x/send.php";
System.Text.ASCIIEncoding ascii = new ASCIIEncoding();
for (int i = 0; i < postdata.Length; i += 2)
{
data2 += string.Format("&{0}={1}", postdata[i], postdata[i + 1]);
}
data2 = data2.Remove(0, 1);
byte[] bytesarr = ascii.GetBytes(data2);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytesarr.Length;
System.IO.Stream streamwriter = request.GetRequestStream();
streamwriter.Write(bytesarr, 0, bytesarr.Length);
streamwriter.Close();
}
Can somebody help me out? Point me in the right direction?
Thanks
More focused answer, based on the spot-on comment provided
After writing to the stream, you should invoke GetResponseStream to actually perform the request:
System.IO.Stream streamwriter = request.GetRequestStream();
streamwriter.Write(bytesarr, 0, bytesarr.Length);
streamwriter.Close();
var response = request.GetResponseStream(); // this will execute the request
// [go on ...]
}
Old answer, spotted the issue but missed the purpose of OP code, left for reference
I'm not able at the moment to verify it in VS but this
System.IO.Stream streamwriter = request.GetRequestStream();
^^^^^^^
should be
System.IO.Stream streamwriter = request.GetResponseStream();
^^^^^^^^
as in: you want to parse the response, not the request (which your code never executes, that's why you don't see the URL being hit).