C# REST API Authenticate with Bearer Token - c#

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?

Related

Why POST use Webrequest always fail but use html form is success?

I spent two days to debug but I can't find error's cause.
App client using WebRequest call servlet result is fail, WebException is "The operation has time out" but When I call servlet by POST method in html form is success. Here is code C#:
public string PostURLRequest(string URL, string postData)
{
try
{
System.Text.Encoding enc =
System.Text.Encoding.GetEncoding("shift_jis");
byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);
System.Net.HttpWebRequest req =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
req.ProtocolVersion = System.Net.HttpVersion.Version10;
req.Method = "POST";
req.ReadWriteTimeout = -1;
req.KeepAlive = false;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataBytes.Length;
req.Timeout = 10*60*1000;
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
reqStream.Close();
System.Net.WebResponse res = req.GetResponse();//----------> THROW EXCEPTION HERE
System.IO.Stream resStream = res.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
String text = sr.ReadToEnd();
sr.Close();
return text;
}
catch(System.Net.WebException ex)
{
if (ex.Status == System.Net.WebExceptionStatus.Timeout)
{
Console.WriteLine("Error: {0}", ex.Message);
}
return "NG";
}
}

I am trying to write a console app in c# that consume a web service running on tomcat, to perform a "PUT" method with an xml file

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);
}

How to stream speech to wit.ai speech end point

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;
}
}

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream getting this error

i am working on asp.net webform to passing json string on a url for authenticate but getting error in Gzip.
here is my method to post data
private static string GetResponse(string requestData, string url)
{
string responseXML = string.Empty;
try
{
byte[] data = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Accept-Encoding", "gzip");
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse webResponse = request.GetResponse();
var rsp = webResponse.GetResponseStream();
if (rsp == null)
{
//throw exception
}
using (StreamReader readStream = new StreamReader(new GZipStream(rsp, CompressionMode.Decompress)))
{
responseXML = JsonConvert.DeserializeXmlNode(readStream.ReadToEnd()).InnerXml;
}
}
catch (WebException webEx)
{
//get the response stream
WebResponse response = webEx.Response;
Stream stream = response.GetResponseStream();
String responseMessage = new StreamReader(stream).ReadToEnd();
}
finally
{
}
return responseXML.ToString();
}
getting this error while i am passing the json object and url
enter image description here

How to send a string to url in window phone?

I create a method in a class (not in phone app) :
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "data=" + str;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
}
but it get error like that :
'System.Net.HttpWebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?
I'm don't know how why?please help me
//Create web request for Post Method
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(SendRequest, req);
}
catch (WebException)
{
}
}
//Get Response and write body
private void SendRequest(IAsyncResult asyncResult)
{
string str = "test";
string Data = "data=" + str;
HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
request.BeginGetResponse(SendResponse, req);
}
//Get Response string
private void SendResponse(IAsyncResult asyncResult)
{
try
{
MemoryStream ms;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
HttpWebResponse httpResponse = (HttpWebResponse)response;
string _responestring = string.Empty;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
_responestring = reader.ReadToEnd();
}
}
catch (WebException)
{
}
}

Categories

Resources