I would like to set a timeout value for httpwebrequest in my C# WinRT code. But httpwebrequest is not available in WinRT. so how please let me know how to set the timeout value for the HttpWebRequest.
Use the HttpClient class to make your request. It has a TimeOut property you can set to your liking.
You can also use the HttpWebRequest class, and it also have a TimeOut property.
In most cases, HttpClient is the way to go, as it is easier to use and you don't need the level of customization the HttpWebRequest provides.
to set timeout to your webrequest you need to set HttpWebRequest.Timeout and it's all .
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("your url");
myHttpWebRequest.Timeout = 1000 ;
Related
I need to create an ASP.NET Core 3 Web API that understand this URL
http://myapp.com/MyASPNetCore3WebApi/myController/myWebMethod?user=A0001
and one zipfile which goes as a content. This is the code that calls the needed API, which I need to create:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URI);
httpWebRequest.Timeout = -1;
httpWebRequest.KeepAlive = false;
httpWebRequest.Method = "POST";
httpWebRequest.ProtocolVersion = HttpVersion.Version10;
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.Accept = "application/octet-stream";
httpWebRequest.ContentLength = data.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The code above is working fine, it is used everyday, sending data to a java web service, now I am replacing that system for a new one in ASP.NET Core and I can't change the caller's code, that's why I need to create a Web API that understand that URL.
I have wrote this code in my Web API, but I guess I am missing something that I can´t figure it out because I get an error ion the client (code above)
[HttpPost("myWebMethod")]
public FileStreamResult myWebMethod(string user, [FromBody] Stream compress)
{
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
.....................
}
The error I get in the client is this:-
[System.Net.WebException] {"The remote server returned an error: (415)
Unsupported Media Type."} System.Net.WebException
Thanks in advance for any help
If the goal is to read the raw request content, this can be done using HttpContext controller property. HttpContext has Request property that provides access to the actual HTTP request.
No additional model properties or controller arguments are needed to access raw request stream. It's important to note that FromBody and FromForm binding should not be used in this case.
There are couple notes regarding the code in the example from the original question.
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
The HttpContext.Request.Body property does not return MemoryStream, it returns its own implementation of a Stream. It means that there is no ToArray method.
When reading the entire content of a request directly into the server's memory, it is better to check the content length, otherwise the client can crash the server by sending a large enough request.
Using *Async methods when reading the content of the request will improve performance.
So I am currently working on making SOAP API request to a service with WCF generated code "Client object", I am wondering how to set the Cookie header to the request?
In general, we add the custom HTTP header by using HttpRequestMessageProperty. Please refer to the below code.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
using (OperationContextScope ocs=new OperationContextScope(client.InnerChannel))
{
var requestProp = new HttpRequestMessageProperty();
requestProp.Headers["myhttpheader"] = "Boom";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProp;
var result = client.SayHelloAsync();
Console.WriteLine(result.Result);
}
Result.
WebOperationContext is a convenience wrapper around the OperationContext. At present, it hasn’t been implemented yet in the Aspnet Core.
https://github.com/dotnet/wcf/issues/2686
Feel free to let me know if there is anything I can help with.
In the application which I am automating, below is the requirement.
Need to run the request in the SOAPUI.
This will generate the token response for the provided request.
We will need to use this token in constructing the URL for opening up the application. The token is driven by timestamp. So this will change for every trigger.
Please let me know if there is a way to fire the SOAP request from Selenium and get the response back or to any file.
I simply used Java code for my Soap requests. For editing data in my XML I used the DOM parser. Here is the code I used for this:
#When("^Soap call is made")
public void soap_call_is_made() throws Exception {
XMLHandling xml = new XMLHandling();
String url = "URL here";
String xmlPath = getClass().getResource("location/of/file.xml").getPath();
Document document = xml.getXMLFile(xmlPath);
SOAPMessage soapResponse =xml.makeSoapCall(document, url);
// print SOAP Response
System.out.print("Response SOAP Message:");
soapResponse.writeTo(System.out);
}
The last line will get the token which is in the response.
Edit:
To get specific data from the response, use:
String tagName = "tagnameYouNeed"
String value = xml.getValueByTagName(soapResponse, tagName);
No, Selenium does not handle SOAP/REST request. Instead, you can use java or cURL to handle this situation. Alternatively you can also check rest-assured for this.
I use this simple way to attach username and password to the SOAP request header. This works fine inside Java boundaries, but I want to be able to call it with my WCF client. How do I do this?
I've tried the following code, but it does not include the credentials in the header:
wsClient.ClientCredentials.UserName.UserName = "Hello";
wsClient.ClientCredentials.UserName.Password = "World";
Thanks in advance!
That is quite awful non-standardized way. It uses custom HTTP Headers so you cannot expect that built in WCF mechanism will magically support such approach. How should WCF know that you want to add custom non-standard HTTP header to HTTP request (not SOAP header)?
Use this:
var proxy = new YourServiceClient();
using (var scope = new OperationContextScope(proxy.InnerChannel))
{
var prop = new HttpRequestMessageProperty();
prop.Headers.Add("UserName", "Hello");
prop.Headers.Add("Password", "World");
OperationContext context = OperationContext.Current;
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = prop;
proxy.CallYourOperation();
}
Below is my request i get a 500 internal server error at getresponse
string requestData = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><h:HeaderItem xmlns:h=\"http://tempuri.org/\">a header item</h:HeaderItem><ActivityId CorrelationId=\"090c553b-bfcc-4e4f-94cd-1b4333fe82a9\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">377a454b-b543-4c6f-b4ac-3981029b60e6</ActivityId></s:Header><s:Body><string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">a body item</string></s:Body></s:Envelope>";
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/WebService/");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentLength = requestDataBytes.Length;
StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
streamWriter.Write(requestData);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseBody = streamReader.ReadToEnd();
I may have an answer for you.
Move the line where you set your headers to the point before you set the content type, and retry your code, as follows:
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentType = "text/xml; charset=utf-8";
I make this suggestion based on the documentation for the ContentType property for the WebRequest object from MS:
MS docs on WebRequest
The value for this property is stored in WebHeaderCollection . If
WebHeaderCollection is set, the property value is lost.
Now, I realize we're not expressly setting the WebHeaderCollection, but you are setting a header in that collection, and it made me suspect at least the possibility of this being a problem - rendering your existing ContentType blank, and being interpreted as some default on the inbound side of the web service.
Maybe a long shot, but it might be worth a try.
You should enable WCF trace logging on your server and see if it indicates an error. Typically errors that occur during deserialization or in the WCF layers before hitting your app code will write to this log.
For more info on setting up WCF trace logging, see here or here.