GetResponse not coming back using HttpWebRequest - c#

Using form contenttype, I am getting stuck at this line:
var webresponse = (HttpWebResponse)webrequest.GetResponse();
For the url, you can use any value. Here is the full code:
public bool test()
{
string url = "https://www.google.com";
// Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
using (Stream postStream = webrequest.GetRequestStream())
{
//
}
// Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
// Normal Completion
return true;
}
Does anyone know why it would get stuck on this line and not come back (when you are doing debugging):
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Thank You

I found the problem! I was calling the method as an async task:
private async Task starttest()
{
clsTester objTester = new clsTester();
objTester.test();
}
...
var result = Task.Run(async () => await starttest());
I removed all that code and changed it to a worker thread:
private Thread workerThread = null;
private void starttest()
{
clsTester objTester = new clsTester();
objTester.test();
}
And then called it as follows:
...
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.starttest));
this.workerThread.Start();
Everything is working now.

Related

Retrieve response and do an action in a HttpWebRespo call, from an IAsyncResult function C#

From my class I call another class that makes a call to an API with an IAsyncResult function that listens when the server responds.
My question is how do I go about when the API responds, take that response and do an action.
My code listens, and grabs the answer, but I'm not managing to do anything with it
winForm.cs:
var response = services.postService(payment,url);
//if response Its OK make somthing
service.cs
public HttpWebRequest request;
private static ManualResetEvent allDone = new ManualResetEvent(false);
public void postService(PayModel paymentObject, String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "pay");
request.ContentType = "application/json";
request.Method = "POST";
var response = request.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, paymentObject)), request);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult,PayModel paymentObject)
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
using (var streamWriter = new StreamWriter(request.EndGetRequestStream(asynchronousResult)))
{
string json = new JavaScriptSerializer().Serialize(paymentObject);
Console.Out.WriteLine(json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var response = request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
streamResponse.Close();
streamRead.Close();
response.Close();
allDone.Set();
frmVenta.closeTransaccion();
}
I tried many things but I can't get the answer, when I put a return on it, it never performs the action, the program continues and does not return
I cant use HttpClient , the program es older.

Too many automatic redirects have been attempted in WebClient

I need to allow redirection in my WebClient 'cause I've this url:
http://int.soccerway.com/national/algeria/ligue-2/c207/
when I add this in the browser I'll get a redirect to this:
http://int.soccerway.com/national/algeria/ligue-2/20172018/regular-season/r43168/
when I perform a request I execute this method:
public static string GetData(string url)
{
HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
try
{
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
webReq.AllowAutoRedirect = true;
webReq.MaximumAutomaticRedirections = 1;
using (WebResponse response = webReq.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
...
}
but this throws an exception:
Too many automatic redirects have been attempted
other threads suggest to add a cookie container, I did so but the error happen occurs again. How can I solve this?

Getting the response of Asynchronous http web request using POST method in asp.net core

I am using asp.net core. I am able to get the response from the http webrequest using GET method. To get the response via http webrequest using POST am facing 405 error.(Remote server not found)
Here is my code using GET Method.
public static void Main(string[] args)
{
var task = MakeAsyncRequest("http://localhost:8080/nifi-api/flow/status", "text/html");
Console.ReadLine();
}
public static Task<string> MakeAsyncRequest(string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = "GET";
request.Proxy = null;
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string results = reader.ReadToEnd();
if (!string.IsNullOrEmpty(results))
{
Data data = new Data();
data = JsonConvert.DeserializeObject<Data>(results);
}
return results;
}
}
Please let me know how to get the response using async POST method in asp.net core. Thanks in advance.
Maybe this way?
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://localhost:8080/nifi-api/flow/status", new StringContent("Json string", Encoding.UTF8, "application/json"));

C# WP8 async HttpWebRequest Post with xml request message

i've been reading here for quite a long time, but in this case i'm not getting any further.
I'm rather new to Windows Phone development and facing the following problem.
I'm calling a webservice were I have to post a xml request message. I've got the code working in regular c# (see code below)
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
But for Windows Phone (8) development it needs to be async. After searching the web, and trying the various samples given here I came to the following code:
private async void DoCallWS()
{
string url = "<my_url>";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string requestXml = "<my_request_xml>";
// convert request to byte array
byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);
// Write the bytes to the stream
await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
//return reader.ReadToEnd();
string result = reader.ReadToEnd();
}
}
}
The string result has the value of my request xml message i'm trying to sent....
I'm aware that async void methodes are not preferred but i will fix that later.
I've also tried to following the solution as described by Matthias Shapiro (http://matthiasshapiro.com/2012/12/10/window-8-win-phone-code-sharing-httpwebrequest-getresponseasync/) but that caused the code to crash
Please point me in the right direction :)
Thnx Frank
What you're doing is only writing to the request stream. You're missing the code which reads from the response.
The reason you're getting back your request xml is that you reset the request stream and read from that exact stream.
Your method should look as follows:
private async Task DoCallWSAsync()
{
string url = "<my_url>";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string requestXml = "<my_request_xml>";
// convert request to byte array
byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml);
// Write the bytes to the stream
await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length);
}
using (WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, httpWebRequest))
{
var responseStream = responseObject.GetResponseStream();
var sr = new StreamReader(responseStream);
string received = await sr.ReadToEndAsync();
return received;
}
}

WP7 Create helper class for easy use HttpWebRequest with POST method

Actually I have something like this:
private void createHttpRequest()
{
System.Uri myUri = new System.Uri("..url..");
HttpWebRequest myHttpRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myHttpRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
string hash = HashHelper.createStringHash("123", "TEST", "0216");
// Create the post data
byte[] byteArray = createByteArrayFromHash(hash);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
ApiResponse apiResponse = (ApiResponse)JsonConvert.DeserializeObject<ApiResponse>(result);
}
}
It's good, it's working but now I must use these methods in every page and just change method createByteArrayFromHash which creates request. What if I want to create helper class that can help me to do this in something about 3 lines of code in page. How would you do that? I was thinking about this way but how to add request before response? Or would you do it another way? Thanks
Yeah, it's better to use async and await. Here is an example of such a wrapper:
public async Task<string> SendRequestGetResponse(string postData, CookieContainer cookiesContainer = null)
{
var postRequest = (HttpWebRequest)WebRequest.Create(Constants.WebServiceUrl);
postRequest.ContentType = "Your content-type";
postRequest.Method = "POST";
postRequest.CookieContainer = new CookieContainer();
postRequest.CookieContainer = App.Session.Cookies;
using (var requestStream = await postRequest.GetRequestStreamAsync())
{
byte[] postDataArray = Encoding.UTF8.GetBytes(postData);
await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
}
var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
if (postResponse != null)
{
var postResponseStream = postResponse.GetResponseStream();
var postStreamReader = new StreamReader(postResponseStream);
// Can use cookies if you need
if (cookiesContainer == null)
{
if (!string.IsNullOrEmpty(postResponse.Headers["YourCookieHere"]))
{
var cookiesCollection = postResponse.Cookies;
// App.Session is a global object to store cookies and etc.
App.Session.Cookies.Add(new Uri(Constants.WebServiceUrl), cookiesCollection);
}
}
string response = await postStreamReader.ReadToEndAsync();
return response;
}
return null;
}
You can modify it as you wish

Categories