I am trying to consume wcf restful service. The code is as follows:
private static string SendRequest(string uri, string method, string contentType, string body)
{
string responseBody = null;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Method = method;
if (!String.IsNullOrEmpty(contentType))
{
req.ContentType = contentType;
}
if (body != null)
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
req.GetRequestStream().Close();
}
req.Accept = "*/*";
HttpWebResponse resp;
resp = (HttpWebResponse)req.GetResponse();
return responseBody;
}
Now the issue is, sometimes it works fine and sometimes i get the error
"the remote server returned an error 403 forbidden."
I cannot figure out why it fails. Any idea???
Related
I have application that sends requests to same REST server constantly and after some time HttpWebRequest.GetResponse() starts timing out i've noticed that whenever i increase System.Net.ServicePointManager.DefaultConnectionLimit it takes it longer to start timing out again, which should mean that those requests are staying active, but as far as i know i'm closing all of them.
Here is method i'm using for my requests.
Current DefaultConnectionLimit is set to 10.
Also there is 1 request that is going on throughout most of applications lifetime.
I'm using .NET Compact framework and REST server is written using WCF (.NET 4.5)
public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using(Stream stream = req.GetResponse().GetResponseStream())
{
using(StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
stream.Close();
stream.Flush();
}
return result;
}
EDIT new version of method:
public static string HttpRequest(string request, string method, string contentType, int timeout)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PodesavanjaManager.TrenutnaPodesavanja.PutanjaServisa + "/" + request);
req.Method = method;
req.ContentType = contentType;
req.Timeout = timeout;
req.KeepAlive = false;
if(method == "POST")
req.ContentLength = 0;
using (HttpWebResponse resp =(HttpWebResponse) req.GetResponse())
{
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
reader.Close();
}
}
}
GC.Collect();
return result;
}
I agree it does behave like the connection is still in use by a resource that has not been closed. The documentation for HttpWebResponse mentions:
You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error.
I was hoping for a more straightforward description like "you must either close the stream returned by GetResponseStream or call the HttpWebResponse.Close method - but if my interpretation of the documentation is correct, your code is fine.
We use HttpWebRequest in our CE applications as well, and always put the response in a using block as well - you could try this:
using(HttpWebResponse response = (HttpWebResponse)req.GetResponse())
using(Stream stream = response.GetResponseStream())
{
// ...
}
Also have you checked your code for other HttpWebRequest usages, just to be sure?
I have a JavaScriptHelper class with a custom WebPost method as follows:
public string WebPost(string url, string json)
{
#region
string responseData = "";
try
{
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
StreamWriter requestWriter = null;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(json);
}
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
webRequest = null;
}
catch (WebException ex)
{
LogBase.LogController.WriteError(ex);
}
catch (Exception ex)
{
LogBase.LogController.WriteError(ex);
}
return responseData;
#endregion
}
I use this to send a POST request to an ASP.NET WebAPI service as follows:
RegisterModel model = new RegisterModel();
model.email = "abc#gmail.com";
model.oAuthId = "11111111";
model.oAuthType = "Facebook";
string jsonStr = JsonConvert.SerializeObject(model);
string response = new JavaScriptHelper().WebPost("http://localhost:9091/api/Authentication/authenticateoauth", jsonStr);
The service receives this call. If the user exists, it returns the response, if it doesnt, it creates the user and returns the response.
The problem I am facing is that when the user exists, everything works fine. I get the response on the client (JSON). When it doesn't exists, it creates the user correctly on the server, but my client breaks off early and doesn't wait for a response. I get the following error:
System.Net.WebException was unhandled
HResult=-2146233079
Message=The remote server returned an error: (500) Internal Server Error.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
How can I force my request to wait for a response a little longer?
I am writing an MVC Web API the make async HttpWebRequest calls. I am getting 2 different exceptions. Below is the method I am using.
The 1st exception is: "This stream does not support seek operations." and it is happening on the responseStream.
The 2nd exception is: "timeouts are not supported on this stream" and that is happening on the MemoryStream content.
What am I doing wrong? I have been Googling but not really finding any solution.
Thanks,
Rhonda
private async Task GetHtmlContentAsync(string requestUri, string userAgent, string referrer, bool keepAlive, TimeSpan timeout, bool forceTimeoutWhileReading, string proxy, string requestMethod, string type)
{
//string to hold Response
string output = null;
//create request object
var request = (HttpWebRequest)WebRequest.Create(requestUri);
var content = new MemoryStream();
request.Method = requestMethod;
request.KeepAlive = keepAlive;
request.Headers.Set("Pragma", "no-cache");
request.Timeout = (Int32)timeout.TotalMilliseconds;
request.ReadWriteTimeout = (Int32)timeout.TotalMilliseconds;
request.Referer = referrer;
request.Proxy = new WebProxy(proxy);
request.UserAgent = userAgent;
try
{
using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
await responseStream.CopyToAsync(content);
}
}
var sr = new StreamReader(content);
output = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
output = string.Empty;
var message = ("The API caused an exception in the " + type + ".\r\n " + requestUri + "\r\n" + ex);
Logger.Write(message);
}
return output;
}
I fixed the issue by adding
content.Position = 0
before new StreamReader line. Now I just need to get it work with GZip compression.
Rhonda
Saving data in windows phone received from WCF/web service .
The response may be received after sometime so how to handle this situation.
Saving data is no problem but How to handel if data is received late
You can use this code (show the code from my project):
public void sendPost(string postData, Action<MyResponse, Exception> callback, CreateResponse creater)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UrlRequest);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "application/json";
webRequest.AllowAutoRedirect = true;
webRequest.BeginGetRequestStream(new AsyncCallback(getRequestStreamCallback), new Request()
{
HttpRequest = webRequest,
PostData = postData,
Url = UrlRequest,
CallBack = callback,
Creater = creater
});
}
private void getRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = request.HttpRequest.EndGetRequestStream(asynchronousResult);
byte[] byteArray = Encoding.UTF8.GetBytes(request.PostData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
request.HttpRequest.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
}
private void getResponseCallback(IAsyncResult asynchronousResult)
{
var request = (Request)asynchronousResult.AsyncState;
try
{
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)request.HttpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var myResponse = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
MyResponse response_obj = request.Creater.CreateResponseObj();
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(myResponse)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(response_obj.GetType());
response_obj = (GYResponse)serializer.ReadObject(stream);
if (request.CallBack != null)
{
request.CallBack.Invoke(response_obj, null);
}
}
}
catch (WebException e)
{
if (request.CallBack != null)
{
request.CallBack.Invoke(null, e);
}
}
}
public void getInfo(string uid, Action<MyResponse, Exception> callback)
{
CreateResponse creater = new CreateResponseGetInfo();
string model = "User";
string method = "getInfo";
Params parametrs = new Params();
parametrs.Uid = uid;
//create yor request
string request = getRequestString(model, method, parametrs, Atoken);
sendPost(request, callback, creater);
}
So, you call method, which send request to web service postRequester.getInfo(uid, ResponseHandler) and use delegate for processing result.
private void ResponseHandler(MyResponse result, Exception error)
{
if (error != null)
{
string err = error.Message;
return;
}
else
{
var infoResponse = result as ResponseGetInfo;
if (infoResponse != null)
{
//result processing..
}
}
}
All the web requests you make in a Windows Phone app are Asynchronous. That means, you make a web request from your app and attach a handler to handle the response when it comes. In the response handler, you will have to take care of the response and do whatever you want with it.
Check this link Using WebClient and HttpWebRequest
I'm using WCF to create some REST service.
One of the Rest Service method need to get byte array as parameter ( picture as byte array ) and return some object.
I run this service using IIS.
But this is not working.
The code that i wrote :
[ServiceContract]
public interface IPicService
{
[OperationContract, WebInvoke(Method="POST", UriTemplate = "GetPicReport/{imageName}")]
Report GetPicReport( string imageName, Stream image );
}
[ServiceBehavior( AddressFilterMode = AddressFilterMode.Any )]
public class PicService: IPicService
{
public Report GetPicReport( string imageName, Stream image )
{
return new Report ();
}
}
I checking this code using explorer - but i get an error about missing parameter ( the image stream )
How can i test it ?
I can't use the WCF Test Client - so i wrote simple application that create http call - and this method return error 404 ( server not found )
Can you try the below code:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "text/xml";
request.Method = method;
}
//var objContent = HttpContentExtensions.CreateDataContract(requestBody);
if(method == "POST" && requestBody != null)
{
//byte[] requestBodyBytes = ToByteArrayUsingXmlSer(requestBody, "http://schemas.datacontract.org/2004/07/XMLService");
byte[] requestBodyBytes = ToByteArrayUsingDataContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
//request.Timeout = 60000;
}
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;
}
}
The post here shows how to implement a service just like yours, along with a test client (using HttpWebRequest). Another thing you can do is to enable tracing at the server, it may tell you why the request is being rejected.