I'm trying to do a direct post to Google using this code. I keep getting an error, "invalid private key". I have double checked it and even had someone else double check it. The reason i'm going it this way is because I'm using javascript and ajax to pass the variables to this function.
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"].ToString();
string strParameters = "?privatekey=" + strPrivateKey +
"&remoteip=" + HttpContext.Request.UserHostAddress.ToString() +
"&challenge=" + captchaChallenge +
"&response=" + captchaResponse;
WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
request.Method = "POST";
string postData = strParameters;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey;
}
else
{
return responseFromServer;
}
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
else
{
errorCodeList.Add(8);
return null;
}
}
The "return" in the IF/ELSE means thet that the "Clean up the streams" code is unreachable and as the return withing the IF would end the execution, this could be simplified a little:
[HttpPost]
public string ValidateReCaptcha(string captchaChallenge, string captchaResponse)
{
if (captchaChallenge != null && captchaResponse != null)
{
// original code, remains unchanged
/*
...snipped for clarity
*/
// Clean up the streams (relocated to make it reachable code)
reader.Close();
dataStream.Close();
response.Close();
if (responseFromServer.ToString() != "true")
{
errorCodeList.Add(8);
return responseFromServer + strPrivateKey; // "IF" ends execution here
}
return responseFromServer; // "ELSE" ends execution here
}
errorCodeList.Add(8);
return null;
}
I guess you need to delete ? on post data.
I've changed the code for me, and this works
private bool ValidarCaptcha(UsuarioMV usuarioMV)
{
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
try
{
string captchaChallenge = usuarioMV.sCaptchaChallenge;
string captchaResponse = usuarioMV.sCaptchaResponse;
if (captchaChallenge != null
&& captchaResponse != null)
{
throw new Exception("Parametros captcha nulos.");
}
WebRequest request = WebRequest.Create("https://www.google.com/recaptcha/api/verify");
request.Method = "POST";
//Solicitud
string strPrivateKey = System.Web.Configuration.WebConfigurationManager.AppSettings["RecaptchaPrivateKey"].ToString();
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("privatekey", strPrivateKey);
outgoingQueryString.Add("remoteip", "localhost");
outgoingQueryString.Add("challenge", captchaChallenge);
outgoingQueryString.Add("response", captchaResponse);
string postData = outgoingQueryString.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
//Respuesta
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
if (reader.ReadLine() != "true")
{
string sLinea = reader.ReadLine();
//if the is another problem
if (sLinea != "incorrect-captcha-sol")
{
throw new Exception(sLinea);
}
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw;
}
finally
{
//Clean up the streams.
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
You can try like this basically. I got affirmative result !!!
public async Task<bool> ReCaptcha(Recaptcha recaptcha)
{
string secretKey = "YOUR_PRIVATE_KEY";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, recaptcha.Response), null);
if (response.IsSuccessStatusCode)
{
var resultString = await response.Content.ReadAsStringAsync();
RecaptchaResponse resp = JsonConvert.DeserializeObject<RecaptchaResponse>(resultString);
if (resp.success)
{
return true;
}
}
return false;
}
Related
I want to display in console the response from request in pretty Xml format, I write code but console displays nothing.
What I want from project is: there some Xml requests (they should work step by step), if (for example) result from first (checkPaymentRequisites) request is equal from 0 and status == 3, then send (go to) second (addOfflinePayment) request. Below codes:
Main method:
public static string postXMLData(string destinationUrl, string xml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
var xmlResponce = XmlToResponce(responseStream);
if (xmlResponce.Providers.checkPaymentRequisites.Payment.result == 0 && xmlResponce.Providers.checkPaymentRequisites.Payment.status == 3)
{
xml=Requests.addOfflinePayment();
}
else
{
Console.WriteLine("Something wrong");
}
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return string.Empty;
}
Responses:
//Responses
//checkPaymentRequisites
private static Responses.Response XmlToResponce (Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(Responses.Response));
var xmlResponce = xmlSerializer.Deserialize(stream) as Responses.Response;
return xmlResponce;
}
//addOfflinePayment
private static Responses.ResponseOff XmlToResOff(Stream stream)
{
var xmlSerializer = new XmlSerializer(typeof(Responses.ResponseOff));
var xmlResponce = xmlSerializer.Deserialize(stream) as Responses.ResponseOff;
return xmlResponce;
}
Diplaying to console:
static void Main(string[] args)
{
string str = Requests.checkPaymentRequisites();
var xml = postXMLData(url, str);
Console.WriteLine(xml);
Console.ReadKey();
}
I tried some copy-past from other place of code to other place )))) (stupid things), no result
public static String TransferMessage(String uri, String resource,
String xml_data, Method httpmethod,
ReturnType returnType)
{
try
{
WebRequest request = WebRequest.Create(uri + resource);
request.Method = httpmethod.ToString();
request.ContentType = #"application/xml;";
//request.Headers.Add("Token", token);
request.Timeout = Convert.ToInt32((new TimeSpan(1, 0, 0)).TotalMilliseconds);
request.ContentLength = Encoding.UTF8.GetByteCount(xml_data);
if (httpmethod != Method.GET)
using (Stream stream = request.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(xml_data), 0,
Encoding.UTF8.GetByteCount(xml_data));
stream.Flush();
stream.Close();
}
return getResponseContent(request.GetResponse());
}
catch(Exception e)
{
Console.WriteLine(e);
}
return null;
}
Main method:
var res_xml = MethodHelper.TransferMessage(endpoint, "/" + resource,xml,
MethodHelper.Method.PUT,
MethodHelper.ReturnType.XML);
I am getting this error
ERROR javax.xml.bind.UnmarshalException\n - with
linked exception:\n[org.xml.sax.SAXParseException; line Number: 1;
columnNumber: 1; Content is not allowed in prolog.]
try{
string contend = "";
using (var streamReader = new StreamReader(new FileInfo(#"C:\Users\absmbez\Desktop\temp\upload.xml").OpenRead()))
{
contend = streamReader.ReadToEnd();
}
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "PUT";
webrequest.ContentType = "application/xml";
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
byte[] requestData = enc.GetBytes(contend);
webrequest.ContentLength = requestData.Length;
using (var stream = webrequest.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
}
I'm having trouble getting a good response from wit.ai's speech end point. The response is always 400. I seem to be following the docs but something's wrong.
Any help would be appreciated.
private string ProcessSpeechStream(Stream stream)
{
BinaryReader filereader = new BinaryReader(stream);
byte[] arr = filereader.ReadBytes((Int32)stream.Length);
filereader.Close();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");
request.SendChunked = true;
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + APIToken;
request.ContentType = "chunked";
request.ContentLength = arr.Length;
var st = request.GetRequestStream();
st.Write(arr, 0, arr.Length);
st.Close();
// Process the wit.ai response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader response_stream = new StreamReader(response.GetResponseStream());
return response_stream.ReadToEnd();
}
else
{
Logger.AILogger.Log("Error: " + response.StatusCode.ToString());
return string.Empty;
}
}
catch (Exception ex)
{
Logger.AILogger.Log("Error: " + ex.Message, ex);
return string.Empty;
}
}
This code sample uses the correct encoding. If you are using Naudio make sure you waveformat is like the encoding (Plus it has to be mono):
private string ProcessSpeechStream(Stream stream)
{
var ms = new MemoryStream();
stream.CopyTo(ms);
var arr = ms.ToArray();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.wit.ai/speech");
request.SendChunked = true;
request.Method = "POST";
request.Headers["Authorization"] = "Bearer " + APIToken;
request.ContentType = "audio/raw;encoding=signed-integer;bits=16;rate=44100;endian=little";
request.ContentLength = arr.Length;
var st = request.GetRequestStream();
st.Write(arr, 0, arr.Length);
st.Close();
// Process the wit.ai response
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader response_stream = new StreamReader(response.GetResponseStream());
return response_stream.ReadToEnd();
}
}
catch (Exception ex)
{
// use your own exception handling class
// Logger.AILogger.Log("Error: " + ex.Message, ex);
return string.Empty;
}
}
Trying to write a tool which downloads a .zip file from a server via REST API.
It works without any problems with SOAP-UI but my tool doesn't want to download any files.
Always getting this error:
Cannot send a content-body with this verb-type.
My POST-Requests work fine but GET-Requests make problems. I Think there is a problem with my Webrequest-Header.
The authentication has to look like this:
Bearer "Access Token"
Here is my code:
class RestProvider
{
protected string method;
protected string endpoint;
protected string resource;
protected string parameters;
public RestProvider(string method, string endpoint, string resource, string parameters)
{
this.method = method;
this.endpoint = endpoint;
this.resource = resource;
this.parameters = parameters;
}
public string GetResponse()
{
string resultString = string.Empty;
ASCIIEncoding enc = new ASCIIEncoding();
byte[] paramData = enc.GetBytes(parameters);
if (this.method == "post")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch(Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
else if(this.method == "get")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(this.parameters));
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch (Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
return resultString;
}
}
Any ideas?
I am sending a URL and XML to a webservices, so that it will return me JSON about the result. I am here posting the request to the webservices how do I get the value from the webservices back. The value returned by the webservices is JSON. What should be the return type here and what should be returned to get the HTTP response status and body
public string HttpPostcredentials(string XML, string url)
{
try
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
req.ContentType = "application/xml";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
}
catch (Exception e)
{
}
return null;
}
Is this what you are looking for:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = "POST";
}
byte[] requestBodyBytes = Encoding.ASCII.GetBytes(XML);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
You need to get the Response from the HttpWebRequest
WebResponse result = req.GetResponse();