C# python http post to C# httpwebrequest - c#

i try to figure it out the black box of the server side that code by python for sending http post. In C# i trying to use httpwebrequest and httpwebresponse to send and receive message back from the server side.
Below is the python code:
**# Request login to server**
import httplib, urllib, requests
import sys, time
from requests.adapters import HTTPAdapter
import select, socket
s = requests.Session()
url = 'http://192.168.1.1/request_login'
data = 'user.login(test,test)' #login account and password set here
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-1)
**# send key file to server**
url = 'http://192.168.1.1/request_sendfile'
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})} # **Don't understand this format**
r = s.post(url, files=files, timeout=30.0)
if r.status_code != 200:
print "Failed sending data file (%d, %s)" % (r.status_code, r.reason)
url = 'http://192.168.1.1/request_sendfile'
data = 'reader.view_log(4)'
r = s.post(url, data=data)
if r.status_code != 200:
print "Failed loging in (%d)" % (r.status_code)
sys.exit(-3)
print "Logs: "
print r.content
sys.exit(-4)
Above is the code for login and sending file to server in one session, i try to use C# do the same way.
I set two http request at the same time, however for the login is success while try to get second http request i get an error of "400" doesn't understand context of verb.
Below is the C# code:
private void httpost()
{
try
{
string Url = "http://192.168.1.1/request_login";
string Urls = "http://192.168.1.1/request_sendfile";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
HttpWebRequest requests = HttpWebRequest.Create(Urls) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "login";
string param = "user.login(test,test)";
byte[] bs = Encoding.ASCII.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
StreamReader sr = new StreamReader(response.GetResponseStream());
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
if(resp.StatusCode == HttpStatusCode.OK)
{
richTextBox1.AppendText("Login Response Status:" + resp.StatusCode + "\n");
}
else
{
richTextBox1.AppendText("Login Response Failed: " + resp.StatusCode + "\n");
}
request.KeepAlive = true;
result = sr.ReadToEnd();
sr.Close();
}
using (Stream importFile = requests.GetRequestStream())
{
FileStream fs = File.OpenRead(#"data.xml");
byte[] bytes = ReadWholeArray(fs); // turn xml file to byte function
requests.ContentType = "application/x-binary";
requests.Method = "POST";
importFile.Write(bytes, 0, bytes.Length);
}
using (WebResponse responses = requests.GetResponse())
{
StreamReader srs = new StreamReader(responses.GetResponseStream());
result = srs.ReadToEnd();
srs.Close();
}
}
catch (Exception ex)
{
richTextBox1.AppendText("Exception Throw:" + ex.Message);
}
}
I try the python code it request login and send file at the same time.
And below is the code that i don't understand.
files = {'file': (data_xml, open(data_xml, 'rb'), 'application/x-binary', {'Expires': '0'})}

Related

Google speech to text API in C# stopped working

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

HttpWebRequest.getResponse() returning NULL

I am attempting to create a console app that sends a WebRequest to a website so that I can get some information back from it in JSON format. Once I build up the request and try to get response I just want to simply print out the data, but when I call httpWebRequest.getResponse() it returns NULL.
I have tried multiple other methods of sending the data to the the url but those are all giving me like 404, or 400 errors, etc. This method at least isn't giving me any error, just a NULL.
Here is a snapshot of the documentation I am using for the API (albeit the docs aren't complete yet):
Here is the console app code that I have right now:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.remot3.it/apv/v27/user/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("developerkey", "***KEY***");
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
email = "***EMAIL***",
password = "***PASSWORD***"
});
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
}
Expected output is some JSON data, but I am getting a NULL back from getResponse().
Try to serialize the credential in your form and for header send as parameter for this class.
Check below for my code. It is not 100 % fit to your requirement, but atleast it will help to get through your logic.
Here is what I get Json Response from this code. Its work Perfect. Please remember to add timeout option on your webrequest and at the end close the streamreader and stream after completing your task. please check this code.
public static string httpPost(string url, string json)
{
string content = "";
byte[] bs;
if (json != null && json != string.Empty)
{
bs = Encoding.UTF8.GetBytes(json);
}
else
{
bs = Encoding.UTF8.GetBytes(url);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (json != string.Empty)
req.ContentType = "application/json";
else
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
//req.UserAgent = "test.net";
req.Accept = "application/json";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
using (WebResponse wr = req.GetResponse())
{
Stream s = wr.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
content = reader.ReadToEnd();
wr.Close();
s.Close();
reader.Close();
}
return content;
}

HttpWebResponse not responding from PHP

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.

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

UnSupported Media Type when Calling REST Web Service

I am calling a REST web service which has given me this documentation
HTTP Method: POST
Path: /commit/{path}/add-node
Response Status 200, 302, 403, 404, 409, 503
Form Parameters
- name : attribute name
- message : commit message
Based on this documentation. I have written following C# code.
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
I also tried
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
var param = new { name = nodeName, message = commitMessage };
Stream reqStream = null;
string output = null;
try {
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
JsonConvert.SerializeObject(param)
);
request.ContentLength = buffer.Length;
reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
} catch (Exception ex) {
.....
}
Unfortunately in both cases, I get 415 Unsupported Media Type in both cases. What is wrong with my code?
The web Services is a REST based web service written in Java.
According to this forum post the ContentType property may not be supported from the Java web service. Are you sure it accepts application/json?

Categories

Resources