HttpWebRequest from a local WCF service - c#

I am doing some testing for a Xamarin Android app with a simple local WCF service to prove my connection code works.
Service:
[OperationContract]
string Ping();
…
public string Ping()
{
return "Pong";
}
Test Code in Xamarin App:
var request = HttpWebRequest.Create(string.Format(#"http://192.168.1.175/_Services/TestService1.svc/Ping"));
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //Errors out here
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
Error:
The remote server returned an error: (400) Bad Request.
Edit:
When using ServiceReference, the following works:
private void button3_Click(object sender, EventArgs e)
{
ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();
string returnString;
returnString = client.Ping();
label1.Text = returnString;
}
Slightly different code still does not work:
private void button4_Click(object sender, EventArgs e)
{
//string serviceUrl = "http://192.168.1.175/_Services/TestService1.svc";
string serviceUrl = "http://localhost/_Services/TestService1.svc";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
httpRequest.Accept = "text/xml";
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
httpRequest.KeepAlive = false;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
{
using (Stream stream = httpResponse.GetResponseStream())
{
label1.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}

The answer was rooted in System.ServiceModel.Activation.WebServiceHostFactory
For some reason none of my sources mentioned this during research for using HttpWebRequest.
I found the reference by chance when looking at Android WCF consuming.
https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/
I got my testing programs working so, I should be able to move forward.

Related

The underlying connection was closed: The connection was closed unexpectedly - WEB FORMS

I'm project in Web Form, and I am passing an array to a method that will make a post to a URL specifies. However, after I run the project and send the array to the method, it breaks with the error stated in the title.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://MINHAURL.COM/QUE-RECEBE-O-POST/");
request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=https://MINHAURL.COM/QUE-RECEBE-O-POST/";
streamWriter.Write(data);
}
WebResponse response = request.GetResponse();
}
private void button1_Click(object sender, EventArgs e)
{
var user = new Usuarios();
var lista = new string[]
{
user.name,
user.dt_nascimento,
user.cidade
};
webBrowser1_DocumentCompleted(lista, null);
}

HttpWebRequest get 404 page only when using POST mode

First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked).
So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello".
But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
string strg = getResponseString(res);
Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);
Although I don't think this is the reason, here's the source of getResponseString:
public static string getResponseString(IAsyncResult asyncResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Position = 0;
webResponse.Close();
return new StreamReader(tempStream).ReadToEnd();
}
This is tested code work fine in Post method with some body. May this gives you an idea.
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/plain; charset=utf-8";
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)
{
}
}
I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.
RestRequest request = new RestRequest("your url", Method.POST);
request.AddParameter("key", value);
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
StoryBoard2.Begin();
string result = response.Content;
if (result.Equals("success"))
message.Text = "Review submitted successfully!";
else
message.Text = "Review could not be submitted.";
indicator.IsRunning = false;
}
else
{
StoryBoard2.Begin();
message.Text = "Review could not be submitted.";
}
});
It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.

Error 401 attempting to retrieve a web response

Whenever I try a "POST" and attempt to get a response, I get a "401 unauthorized access exception".
The application I am trying to develop is automated Texts to remind me of certain events using the TextNow website.
I have looked around the internet and found that I should use NetworkCredentials to allow me to grab a response, but to no avail. I read around somewhere that because of how HTTP interaction in C# works, that it can't recognize a JSON 401 and retry with an authenticated header. How do I fix this?
namespace HTTPWebTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void snd_Click(object sender, EventArgs e)
{
string pnum = number.Text;
string msg = text.Text;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("https://www.textnow.com/api/users/[redacted username]/messages"));
WebResponse response = null;
NetworkCredential netCredential =
new NetworkCredential("[redacted username]", "[redacted password]");
req.Credentials = netCredential;
req.PreAuthenticate = true;
req.Method = "GET";
response = (HttpWebResponse)req.GetResponse(); //error occurs here <<<<<<<<<<<
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
req.Referer = "https://www.textnow.com/api/users/[redacted username]/messages";
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.ContentType = "application/json";
StringBuilder postData = new StringBuilder();
postData.Append("%7B%22contact_value%22%3A%22" + pnum + "%22%2C");
postData.Append("%22contact_type%22%3A2%2C");
postData.Append("%22message%22%3A%22" + msg + "%22%2C");
postData.Append("%22read%22%3A1%2C");
postData.Append("%22message_direction%22%3A2%2C");
postData.Append("%22message_type%22%3A1%2C");
postData.Append("%22date%22%3A%22Sat+Nov+30+2013+13%3A20%3A44+GMT-0800+(Pacific+Standard+Time)%22%2C");
postData.Append("%22from_name%22%3A%22[Redacted]%22%7D");
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(postData.ToString());
response = (HttpWebResponse)req.GetResponse();
}
}
}
I had forgotten to include several custom headers that the server required.
For Example:
req.Headers.Add("Access-Control-Request-Headers","accept, origin, x_session, content-type");
req.Headers.Add("Access-Control-Request-Method","POST");
Fiddler:

C# Soap Web Service WSDL

I have generated stubs from a wsdl file in a asp.net web app. My question is how do i add those function calls to a httpwebrequest? I have gotten this far but dont know how to finish it off and send the soap off on the wire.
public HttpWebRequest CreateWebRequest(string webMethod)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("");
webRequest.Headers.Add(#"SOAPAction", "\"http://www.multispeak.org/Version_3.0/"+ webMethod +"\"");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
protected void Button1_Click(object sender, EventArgs e)
{
MR_ServerSoapClient soapClient = new MR_ServerSoapClient(endPoint,uri);
PingURLRequest request = new PingURLRequest();
PingURLResponse response = new PingURLResponse();
}
I am not sure why you would not use the client methods generated for you, but:
using (var response = (HttpWebResponse)webRequest.GetResponse())
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
}

C# connection to webservice

I have the following code. I need to make a connection to a URL and
POST some data and need to get some data back.
Here is my code :
class Data
{
private int id;
private string date;
}
private void button2_Click(object sender, EventArgs e)
{
string URL = "URL";
Data d = new Data();
d.id = 12345678;
d.date = "25-10-2019";
string Data = JsonConvert.SerializeObject(d);
HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;
if (!string.IsNullOrEmpty(Data))
{
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(Data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
MessageBox.Show(response);
}
}
}
By the statment : using (var streamWriter = new StreamWriter(request.GetRequestStream()))
I got the error System.Net.WebException: 'The remote server returned an error: (502) Bad Gateway.'
And by the statement using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
I got the error "System.Net.WebException: 'The remote server returned an error: (500) Internal Server Error.' "
Please help.

Categories