WEB API C# REPONSE HANGS (HttpWebResponse)http.GetResponse() - c#

Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}

change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.

Related

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

How get cognos report using siteminder token in c#.net

I am trying to get cognos report using siteminder token, below is my code.
string cognosUrl = "https://cognos.blah.com";
string reportPath = "/c10/cgi-bin/cognosisapi.dll/rds/reportData/report/"; string reportId = "ildjfsldkf"; //prod
cognosUrl += string.Concat(reportPath, reportId,"?blahblah");
string targetUrl = cognosUrl;
string strFormvalues = string.Concat("TARGET=",targetUrl);
ASCIIEncoding encoder = new ASCIIEncoding();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
byte[] data = encoder.GetBytes(strFormvalues);
request.AllowAutoRedirect = false;
request.Timeout = 120000;
request.ContentLength = data.Length;
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Cookie,"SMSESSION="+stoken);
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(json);
MemoryStream restream = new MemoryStream(byteArray);
using (Stream output = File.OpenWrite(#"c:\\Projects\\Test_"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".txt"))
using (Stream input = restream)
{
if (input != null) input.CopyTo(output);
}
// var results = serializer.DeserializeObject(json);
reader.Close();
dataStream.Close();
response.Close();
But I am getting response as " DPR-ERR-2101 Your request was invalid.Please contact your administrator."
I am not using C# myself, but a few recommendations while debugging this:
If you are only posting a URL, why not use GET instead of POST?
Try paste the targetURL in your browser, see what happens.
In my setup, when I paste the URL in the browser, I am always redirected before I receive an answer. (to a URL like, /cgi-bin/cognosisapi.dll/rds/sessionOutput/conversationID/i292ED29A62474697AD44306A388F5BBB You are preventing that to happen, that might be an issue)
Hope that helps.

Request uri too long with webservice

I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.

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?

Restful wcf Service error 'Unable to deserialize XML body with root name

I have written a RESFful service for a phone app.
I am not sure what am I doing wrong? I tried to test it with multiple content type settings but no luck.
The data from a phone app is coming encoded in following format.
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
This is the definition in the interface:
[OperationContract]
[WebInvoke]
String GetUserInfo(String authenticateRequest);
I get error: with following test code.
'Unable to deserialize XML body with root name 'Binary' and root namespace '' (for operation 'GetMobileCheckCapture' and contract ('IMobileCC', 'http://tempuri.org/')) using DataContractSerializer
This is how I am trying to test the service:
String encryptedSAML =
PHNhbWxwOlJlc3BvbnNlIHhtbG5zOnNhbWxwPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6cHJvdG9jb2wiPjxzYW1scDpTdGF0dXM+PHNhbWxwOlN0YXR1c0NvZGU+ aGVyVmFsdWU+PC94ZW5jOkNpcGhlckRhdGE+PC94ZW5jOkVuY3J5cHRlZERhdGE+PC9zYW1sOkVuY3J5cHRlZEFzc2VydGlvbj48L3NhbWxwOlJlc3BvbnNlPg==";
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(bDataToPass, 0, bDataToPass.Length);
}
try
{
using (WebResponse webresponse = req.GetResponse())
{
StreamReader reader = null;
string responses = "";
string StatusDescription = ((HttpWebResponse)webresponse).StatusDescription;
if (((HttpWebResponse)webresponse).StatusCode != HttpStatusCode.OK)
{
// Console.Write();
}
reader = new StreamReader(webresponse.GetResponseStream());
responses = reader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(responses.Replace("&", "&"));
response = xmldoc;
}
}
catch (WebException e)
{
using (WebResponse response2 = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response2;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response2.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
Have you tried to use UTF-8 encoding instead of ASCII?
HttpWebRequest req = WebRequest.Create("http://localhost/Services/Mservice.svc/GetUserInfo") as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml; encoding='utf-8'";
UTF8Encoding encoding = new UTF8Encoding();
byte[] bDataToPass = encoding.GetBytes(encryptedSAML);
req.ContentLength = bDataToPass.Length;

Categories

Resources