// // THttpClient.cs // // Begin: Oct 5, 2008 // Authors: // Brian O'Neil // // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/using using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Collections; namespace Thrift.Transport { class THttpClient : TTransport { private Uri _url = null; private MemoryStream _requestStreamBuffer = new MemoryStream(); private Stream _inputStream = null; private int _connectTimeout = 0; private int _readTimeout = 0; private Dictionary _customHeaders = new Dictionary(); public THttpClient(String url) { try { _url = new Uri(url); } catch (IOException iox) { throw new TTransportException(iox.ToString()); } } public void SetConnectTimeout(int timeout) { _connectTimeout = timeout; } public void SetReadTimeout(int timeout) { _readTimeout = timeout; } public void SetCustomHeaders(Dictionary headers) { _customHeaders = headers; } public void SetCustomHeader(String key, String value) { if (_customHeaders == null) { _customHeaders = new Dictionary(); } _customHeaders.Add(key, value); } public override void Open() { } public override void Close() { if (null != _inputStream) { try { _inputStream.Close(); } catch (IOException) { } _inputStream = null; } } public override bool IsOpen { get { return true; } } public override int Read(byte[] buf, int off, int len) { if (_inputStream == null) { throw new TTransportException("Response buffer is empty, no request."); } try { int ret = _inputStream.Read(buf, off, len); if (ret == -1) { throw new TTransportException("No more data available."); } return ret; } catch (IOException iox) { throw new TTransportException(iox.ToString()); } } public override void Write(byte[] buf, int off, int len) { _requestStreamBuffer.Write(buf, off, len); } public override void Flush() { // Extract request and reset buffer byte[] data = _requestStreamBuffer.ToArray(); _requestStreamBuffer = new MemoryStream(); try { // Create connection object HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(_url); // Timeouts, only if explicitly set if (_connectTimeout > 0) { connection.Timeout = _connectTimeout; } if (_readTimeout > 0) { connection.ReadWriteTimeout = _readTimeout; } // Make the request connection.ContentType = "application/x-thrift"; connection.Accept = "application/x-thrift"; connection.UserAgent = "Java/THttpClient"; connection.Method = "POST"; //add custom headers here foreach (KeyValuePair item in _customHeaders) { connection.Headers.Add(item.Key, item.Value); } connection.Proxy = null; connection.ContentLength = data.Length; Stream requestStream = connection.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Flush(); _inputStream = connection.GetResponse().GetResponseStream(); } catch (IOException iox) { throw new TTransportException(iox.ToString()); } } } }