Download Stream with RestSharp and ResponseWriter - http

I donwnload a stream with RestSharp by using the ResponseWriter.
var client = new RestClient
var request = new RestRequest();
// ...
request.ResponseWriter = (ms) => {
// how to detect the status code
};
var response = client.Execute(request);
How can I found out the HTTP Status Code in the ResponseWriter?
Is there a better way to download a Stream?

You can check response.StatusCode and response.StatusDescription after executing the request.
Interestingly, if you use the DownloadData method as described here https://github.com/restsharp/RestSharp/wiki/Other-Usage-Examples there is no way to access this information as far as I can tell.

Currently You can use property AdvancedResponseWriter instead ResponseWriter.
The main difference is that AdvancedResponseWriter in addition to Response Stream gets IHttpResponse and You can check Response Status.
It should be working properly from version 106.6.
https://github.com/restsharp/RestSharp/issues/1207

Related

Simulating response timeouts with ASP.NET Web API

Suppose I have a client that continually requests streams from a service, and I want automate testing it. So, as part of the test, I create a service that returns a stream. The following code snippet constructs the response and returns it:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(fstream);
response.Content.Headers.ContentType = mediaType;
return response;
This works for the success case where the client calls the API and gets a response in a timely manner. But I also want to simulate some timeout failures.
If I want to simulate timeouts before any part of the response is returned, i can simply add a Thread.Sleep() before return response.
My question is: how can I simulate the timeout case where the service has already started return response? I would like to simulate the service timing out after the response headers have been sent, but before the entirety of fstream is sent.
Maybe try something like this?
var response = HttpContext.Current.Response;
response.Buffer = false;
response.AddHeader("SomeHeader","SomeValue");
response.Write("Some body text.");
System.Threading.Thread.Sleep(WEB_SERVER_TIMEOUT_VALUE + 1);

How to Read the message Body in a HTTP POST in Netty (version >= 4.x)

In my server handler;
- channelRead() always gets the msg as HTTPRequest and there I cannot find any place to get the POST request payload.
Then I tried following in my handler to check if it works. The decoder has 0 elements.
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
In my server pipeline I have HttpServerCodec and a custom handler only.
It's likely that your HTTP request is chunked. You should try to add an io.netty.handler.codec.http.HttpObjectAggregator to your pipeline, just after the codecs. It will give a FullHttpRequest to your handler.
ChannelPipeline p = ...;
...
p.addLast("encoder", new HttpResponseEncoder());
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("aggregator", new HttpObjectAggregator(1048576));
...
p.addLast("handler", new MyServerHandler());
Alternatively, you could check this example where HttpRequest and HttpContent are handled separately.
As Leo Gomes mentioned, HTTP Request maybe chunked. so add HttpObjectAggregator before your own handler in pipeline.
if HTTP POST request body is Simple Json String. You can parse it in your own handler like this:
private String parseJosnRequest(FullHttpRequest request){
ByteBuf jsonBuf = request.content();
String jsonStr = jsonBuf.toString(CharsetUtil.UTF_8);
return jsonStr;
}

Get HTTP Response from a url by using C#

Environment: ASP.Net MVC 4 using C#
I need to get image by using GET request to a URL /inbound/faxes/{id}/image
I used the code below
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("/inbound/faxes/238991717/image");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader stream = new StreamReader(response.GetResponseStream());
but it flags "URL not valid"
I used the complete URL www.interfax.net/inbound/faxes/{id}/image
but the result is same
I want to follow this article to receive faxes
Accepting incoming fax notifications by callback
Can anyone help me to get fax...?
Try like this:
using (var client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.interfax.net/inbound/faxes/{id}/image");
}
Notice how the url is prefixed with the protocol (HTTP in this case). Also make sure you have replaced the {id} part of the url with the actual id of the image you are trying to retrieve.

How to return error pages with body using HttpListener/HttpListenerResponse

I'm in the process of creating a REST API using HttpListener in .NET (C#). This all works out great, except for one slight issue.
I'm trying to return responses with Status Codes other than OK (200), for instance ResourceNotFound (404).
When I set the StatusCode of the HttpListenerResponse to something other than 200, and create a response body (using HttpListenerResponse.OutputStream), it seems to be resetting the status code to 200. I'm not able to send a response with StatusCode 404 and a message body. However, this should be possible according to the HTTP specs. I'm checking the requests and responses with Fiddler, but I'm not able to get what I'm looking for.
I've had the same problem and found the source of the problem :
If you write the body in the OutputStream before set the StatusCode (or any other property), the response will be sent before the modification is applied !
So, you have to proceed in this order :
public void Send(HttpListenerContext context, byte[] body)
{
// First, set a random status code and other stuffs
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.ContentType = "text/plain";
// Write to the stream IN LAST (will send request)
context.Response.OutputStream.Write(body, 0, body.Length);
}

How to make URLLoader return an AsyncToken?

I was trying to retrieve binary data over HTTP for my Flex application, and was running into some stumbling blocks. HTTPService did not seem to deal with binary data well, people said to use URLLoader. But URLLoader does not have the nice AsyncToken/IResponder interface that HTTPService provides.
So, I did some searching and could not find anyone extending URLLoader to provide this kind of functionality. I went ahead and took a stab at it myself: http://pastebin.com/d7369d0e0
Basically it wraps a URLLoader and an AsyncToken, and maps the COMPLETE, IO_ERROR, and SECURITY_ERROR events from URLLoader to results/faults that get raised on the AsyncToken.
Basic usage:
var tidbitLoader:AsyncURLLoader = new AsyncURLLoader();
tidbitLoader.dataFormat = URLLoaderDataFormat.BINARY;
var asyncToken:AsyncToken = tidbitLoader.load(new URLRequest("http://localhost/SampleTidbit.swf"));
asyncToken.addResponder(this);
public function result(resultEvent:Object):void
{
trace("result");
}
public function fault(faultEvent:Object):void
{
var fault:FaultEvent = faultEvent as FaultEvent;
trace("fault: " + fault.toString());
}
Is this the right way to approach the problem? Are there existing solutions? I would love to hear feedback.
Thanks,
Karthik
Use the resultFormat = text on the HTTPService and then create a new ByteArray and call writeUTFBytes to write the text from the HTTPService result to the ByteArray. Then you should be able to set that ByteArray to a SWFLoader.source or call Loader.loadBytes.
I have tried your solution James with an AIR 1.5 app, but I get the following error when I set the ByteArray on my SWFLoader.source. Any ideas? I thought I read somewhere that AIR changes the HTTP headers and this may be the cause? Thanks Ben.
[DEBUG] mx.messaging.Channel 'direct_http_channel' channel sending message:
(mx.messaging.messages::HTTPRequestMessage)#0
body = (Object)#1
clientId = (null)
contentType = "application/x-www-form-urlencoded"
destination = "DefaultHTTP"
headers = (Object)#2
httpHeaders = (Object)#3
messageId = "3044E76C-CF0E-2D5F-96BE-74CFF62098B0"
method = "GET"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "http://www.myurl.com/test.jpg"
[INFO] mx.messaging.Producer '4FA2CCF4-2B3E-4EAB-2873-74CFF612AA72' producer connected.
[INFO] mx.messaging.Producer '4FA2CCF4-2B3E-4EAB-2873-74CFF612AA72' producer acknowledge of '3044E76C-CF0E-2D5F-96BE-74CFF62098B0'.
[INFO] mx.rpc.http.HTTPService Decoding HTTPService response
[DEBUG] mx.rpc.http.HTTPService Processing HTTPService response message:
(mx.messaging.messages::AcknowledgeMessage)#0
body = "ÿØÿà
Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.

Resources