GetResponseHeader() public method

public GetResponseHeader ( string headerName ) : string
headerName string
return string
Exemplo n.º 1
0
 internal Response(HttpWebResponse response)
 {
     using (response)
     {
         using (Stream response_stream = response.GetResponseStream())
         {
             if (response_stream.CanRead)
             {
                 byte[] buffer = new byte[16654];
                 int read;
                 using (MemoryStream s = new MemoryStream())
                 {
                     while((read = response_stream.Read(buffer, 0, buffer.Length)) > 0)
                     {
                         s.Write(buffer, 0, read);
                     }
                     Body = new byte[s.Length];
                     s.Seek(0, SeekOrigin.Begin);
                     s.Read(Body, 0, Body.Length);
                 }
             }
         }
         Status = response.StatusCode;
         ContentType = response.GetResponseHeader("Content-Type");
         ETag = response.GetResponseHeader("ETag");
     }
 }
        public ASOptionsResponse(HttpWebResponse httpResponse)
        {
            // Get the MS-ASProtocolCommands header to determine the
            // supported commands
            commands = httpResponse.GetResponseHeader("MS-ASProtocolCommands");

            // Get the MS-ASProtocolVersions header to determine the
            // supported versions
            versions = httpResponse.GetResponseHeader("MS-ASProtocolVersions");
        }
Exemplo n.º 3
0
 public string GetResponseHeader(string headerName)
 {
     if (_raw == null)
     {
         throw new NotImplementedException("Can not call method without existing underlying HttpWebResponse");
     }
     return(_raw.GetResponseHeader(headerName));
 }
Exemplo n.º 4
0
        public override void Handle(HttpWebResponse web_response)
        {
            string header = web_response.GetResponseHeader("Location");

            if (header != null)
            {
                this._context.Fifa.next_url = header;
            }
            else
                throw new RequestException<SignInPage>("Unable to find Location Header");
        }
 private static IEnumerable<KeyValuePair<string, string>> ExtractHeaderFrom(HttpWebResponse webResponse)
 {
     return webResponse
         .Headers
         .AllKeys
         .Select(
             headerKey =>
                 new KeyValuePair<string, string>(
                     headerKey,
                     webResponse.GetResponseHeader(headerKey))).ToList();
 }
 private void CopyHeaderValues(HttpWebResponse response)
 {
     var keys = response.Headers.Keys;
     _headerNames = new string[keys.Count];
     _headers = new Dictionary<string, string>(keys.Count, StringComparer.OrdinalIgnoreCase);
     for (int i = 0; i < keys.Count; i++)
     {
         var key = keys[i];
         var headerValue = response.GetResponseHeader(key);
         _headerNames[i] = key;
         _headers.Add(key, headerValue);
     }
     _headerNamesSet = new HashSet<string>(_headerNames, StringComparer.OrdinalIgnoreCase);
 }
Exemplo n.º 7
0
        public override void Handle(HttpWebResponse web_response)
        {
            string header = web_response.GetResponseHeader("Location");

            if (header != null)
            {
                this._context.Fifa.next_url = header;

                if (web_response.Cookies.Count == 0)
                    throw new RequestException<SetPropertys>("Unable to find Cookie Headers");
            }
            else
                throw new RequestException<SetPropertys>("Unable to find Location Header");
        }
Exemplo n.º 8
0
        public override void Handle(HttpWebResponse web_response)
        {
            string header = web_response.GetResponseHeader("Location");

            if (header != null)
            {
                this._context.Fifa.next_url = header;

                Cookie cookie = web_response.Cookies["webun"];
                if (cookie != null)
                {
                    if (!cookie.Value.Contains(this._context.Authentication.UserName))
                        throw new RequestException<Login>("Wrong Login Info");
                }
                else
                    throw new RequestException<Login>("Unable to find webun Cookie");

            }
            else
                throw new RequestException<Login>("Unable to find Location Header");
        }
Exemplo n.º 9
0
 /// <summary>
 /// Create a SimpleVoc value from a WebResponse for a given key asynchronously
 /// </summary>
 /// <param name="res"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 private async Task<SimpleVocValue> GetValueFromResponseAsync(HttpWebResponse res, string key)
 {
     return new SimpleVocValue
     {
         Key = key,
         Data = await GetResponseDataAsync(res),
         Created = DateTime.Parse(res.GetResponseHeader("x-voc-created")),
         Expires = !string.IsNullOrWhiteSpace(res.GetResponseHeader("x-voc-expires")) ? DateTime.Parse(res.GetResponseHeader("x-voc-expires")) : DateTime.MinValue,
         Flags = int.Parse(res.GetResponseHeader("x-voc-flags")),
         Extended = !string.IsNullOrWhiteSpace(res.GetResponseHeader("x-voc-extended")) ? (Dictionary<string, string>)_serializer.DeserializeObject(res.GetResponseHeader("x-voc-extended")) : null
     };
 }
        public static DateTime GetExpiresHeader(HttpWebResponse response)
        {
            string expires = response.GetResponseHeader("Expires");
            if (expires != null && expires != String.Empty && expires.Trim() != "-1")
            {
                try
                {
                    DateTime expiresDate = DateTime.Parse(expires, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                    return expiresDate;
                }
                catch (Exception ex)
                {
                    // look for ANSI c's asctime() format as a last gasp
                    try
                    {
                        string asctimeFormat = "ddd' 'MMM' 'd' 'HH':'mm':'ss' 'yyyy";
                        DateTime expiresDate = DateTime.ParseExact(expires, asctimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces);
                        return expiresDate;
                    }
                    catch
                    {
                    }

                    Trace.Fail("Exception parsing HTTP date - " + expires + ": " + ex.ToString());
                    return DateTime.MinValue;
                }
            }
            else
            {
                return DateTime.MinValue;
            }
        }
Exemplo n.º 11
0
        private void UpdateLwssoTokenFromResponse(HttpWebResponse httpResponse)
        {
            //update security token if it was modified
            String setCookieAll = httpResponse.GetResponseHeader("Set-Cookie");
            String[] setCookies = setCookieAll.Split(';');
            foreach (String setCookie in setCookies)
            {
                if (setCookie.StartsWith(LWSSO_COOKIE_NAME))
                {
                    String[] setCookiesParts = setCookie.Split('=');
                    lwssoToken = setCookiesParts[1];

                }
            }
        }
Exemplo n.º 12
0
 public string GetResponseHeader(string headerName) => _httpWebResponse.GetResponseHeader(headerName);
        /// <summary>
        /// Handle a 3xx redirect status.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <param name="statusCode">
        /// The status Code.
        /// </param>
        private void HandleRedirect(State state, HttpWebResponse response, HttpStatusCode statusCode)
        {
            Debug.WriteLine("got HTTP redirect " + statusCode);

            if (state.RedirectCount >= DownloaderService.MaxRedirects)
            {
                throw new StopRequestException(ExpansionDownloadStatus.TooManyRedirects, "too many redirects");
            }

            string header = response.GetResponseHeader("Location");
            if (header == null)
            {
                return;
            }

            Debug.WriteLine("Redirecting to " + header);

            string newUri;
            try
            {
                newUri = new URI(this.downloadInfo.Uri).Resolve(new URI(header)).ToString();
            }
            catch (URISyntaxException)
            {
                Debug.WriteLine("Couldn't resolve redirect URI {0} for {1}", header, this.downloadInfo.Uri);
                throw new StopRequestException(ExpansionDownloadStatus.HttpDataError, "Couldn't resolve redirect URI");
            }

            ++state.RedirectCount;
            state.RequestUri = newUri;
            if ((int)statusCode == 301 || (int)statusCode == 303)
            {
                // use the new URI for all future requests (should a retry/resume be necessary)
                state.NewUri = newUri;
            }

            throw new RetryDownloadException();
        }
 /// <summary>
 /// Initially used via a response callback for commands which expect a async response 
 /// </summary>
 /// <param name="webResponse">the HttpWebResponse that will be sent back to the user from the request</param>
 protected virtual void ResponseCallback(HttpWebResponse webResponse)
 {
     //Track and throw up the X-ms request id (x-ms-request-id)
     MsftAsyncResponseId = webResponse.GetResponseHeader("x-ms-request-id");
     ElastaLogger.MessageLogger.Trace("Hosted Service Response Id: {0}", MsftAsyncResponseId);
     for (;;)
     {
         var asyncCommand = new GetAsyncStatusCommand
                                {
                                    HttpVerb = HttpVerbGet,
                                    SubscriptionId = SubscriptionId,
                                    OperationId = MsftAsyncResponseId,
                                    ServiceType = "operations",
                                    Certificate = Certificate
                                };
         asyncCommand.Execute();
         Thread.Sleep(1000);
         OperationStatus status = asyncCommand.GetOperationStatus();
         switch (status)
         {
             case OperationStatus.InProgress:
                 break;
             case OperationStatus.Failed:
                 ElastaLogger.MessageLogger.Error("Hosted Service Response Id: {0}", MsftAsyncResponseId);
                 SitAndWait.Set();
                 return;
             case OperationStatus.Succeeded:
                 ElastaLogger.MessageLogger.Trace("Hosted Service Response Id: {0}", MsftAsyncResponseId);
                 SitAndWait.Set();
                 return;
         }
     }
 }
        /// <summary>
        /// Handle a 503 Service Unavailable status by processing the Retry-After header.
        /// </summary>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        private static void HandleServiceUnavailable(State state, HttpWebResponse response)
        {
            string header = response.GetResponseHeader("Retry-After");
            Debug.WriteLine("DownloadThread : got HTTP response code 503 (retry after {0})", header);

            state.CountRetry = true;
            int retryAfter;
            int.TryParse(header, out retryAfter);

            state.RetryAfter = Math.Max(retryAfter, 0);

            if (state.RetryAfter < DownloaderService.MinimumRetryAfter)
            {
                state.RetryAfter = DownloaderService.MinimumRetryAfter;
            }
            else if (state.RetryAfter > DownloaderService.MaxRetryAfter)
            {
                state.RetryAfter = DownloaderService.MaxRetryAfter;
            }

            state.RetryAfter += Helpers.Random.Next(DownloaderService.MinimumRetryAfter + 1);
            state.RetryAfter *= 1000;

            throw new StopRequestException(
                ExpansionDownloadStatus.WaitingToRetry, "got 503 Service Unavailable, will retry later");
        }
Exemplo n.º 16
0
        /*
        private static Stream GetStreamForResponse(HttpWebResponse webResponse)
        {
            Stream stream;
            switch (webResponse.ContentEncoding.ToUpperInvariant())
            {
                case "GZIP":
                    stream = new GZipStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;
                case "DEFLATE":
                    stream = new DeflateStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;

                default:
                    stream = webResponse.GetResponseStream();
                    //stream.ReadTimeout = readTimeOut;
                    break;
            }
            return stream;
        }
        */

		private IOResponse ReadWebResponse(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service) {
			IOResponse response = new IOResponse ();
            
            
			// result types (string or byte array)
			byte[] resultBinary = null;
			string result = null;
            
			string responseMimeTypeOverride = webResponse.GetResponseHeader ("Content-Type");
            
			using (Stream stream = webResponse.GetResponseStream()) {
				SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");
				if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
                    
					int lengthContent = -1;
					if (webResponse.GetResponseHeader ("Content-Length") != null && webResponse.GetResponseHeader ("Content-Length") != "") {
						lengthContent = Int32.Parse (webResponse.GetResponseHeader ("Content-Length"));
					}
					// testing log line
					// SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
					int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
					if (lengthContent >= 0 && lengthContent<=bufferReadSize) {
						bufferReadSize = lengthContent;
					}
                    
					if(lengthContent>MAX_BINARY_SIZE) {
						SystemLogger.Log (SystemLogger.Module.CORE, 
						                  "WARNING! - file exceeds the maximum size defined in platform (" + MAX_BINARY_SIZE+ " bytes)");
					} else {
						// Read to end of stream in blocks
						SystemLogger.Log (SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
						MemoryStream memBuffer = new MemoryStream ();
						byte[] readBuffer = new byte[bufferReadSize];
						int readLen = 0;
						do {
							readLen = stream.Read (readBuffer, 0, readBuffer.Length);
							memBuffer.Write (readBuffer, 0, readLen);
						} while (readLen >0);
						
						resultBinary = memBuffer.ToArray ();
						memBuffer.Close ();
						memBuffer = null;
					}
				} else {
					SystemLogger.Log (SystemLogger.Module.CORE, "reading response content...");
					using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
						result = reader.ReadToEnd ();
					}
				}

			}

			/*************
			 * CACHE
			 *************/

			// preserve cache-control header from remote server, if any
            /*
			string cacheControlHeader = webResponse.GetResponseHeader ("Cache-Control");
			if (cacheControlHeader != null && cacheControlHeader != "") {
				SystemLogger.Log (SystemLogger.Module.CORE, "Found Cache-Control header on response: " + cacheControlHeader + ", using it on internal response...");
				if(response.Headers == null) {
					response.Headers = new IOHeader[1];
				}
				IOHeader cacheHeader = new IOHeader();
				cacheHeader.Name = "Cache-Control";
				cacheHeader.Value = cacheControlHeader;
				response.Headers[0] = cacheHeader;
			}
             */

            
            /*************
			 * HEADERS HANDLING
			 *************/
            if (webResponse.Headers != null)
            {   
                response.Headers = new IOHeader[webResponse.Headers.Count];
                
                int size = 0;
                foreach(string headerKey in webResponse.Headers.AllKeys) {
                    string headerValue = webResponse.GetResponseHeader(headerKey);
                    IOHeader objHeader = new IOHeader();
				    objHeader.Name = headerKey;
				    objHeader.Value = headerValue;
                    SystemLogger.Log(SystemLogger.Module.CORE, "Found Header on response: " + headerKey + "=" + headerValue);
                    response.Headers[size++] = objHeader;
                }
            }

			/*************
			 * COOKIES HANDLING
			 *************/

			// get response cookies (stored on cookiecontainer)
			if (response.Session == null) {
				response.Session = new IOSessionContext ();
				
			}
            
			response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
			IEnumerator enumerator = this.cookieContainer.GetCookies (webRequest.RequestUri).GetEnumerator ();
			int i = 0;
			while (enumerator.MoveNext()) {
				Cookie cookieFound = (Cookie)enumerator.Current;
				SystemLogger.Log (SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
				IOCookie cookie = new IOCookie ();
				cookie.Name = cookieFound.Name;
				cookie.Value = cookieFound.Value;
				response.Session.Cookies [i] = cookie;
				i++;
			}

			if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
				if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals (contentTypes [service.Type])) {
					response.ContentType = responseMimeTypeOverride;
				} else {
					response.ContentType = contentTypes [service.Type];
				}
				response.ContentBinary = resultBinary; // Assign binary content here
			} else {
				response.ContentType = contentTypes [service.Type];
				response.Content = result;
			}

            
			return response;

		}
        private static bool? ProcessResponse(HttpWebResponse response)
        {
            bool isSubscribed;
            if (!bool.TryParse(response.GetResponseHeader(QuickPulseConstants.XMsQpsSubscribedHeaderName), out isSubscribed))
            {
                return null;
            }

            return isSubscribed;
        }
        /// <summary>
        /// Read headers from the HTTP response and store them into local state.
        /// </summary>
        /// <param name="innerState">
        /// The inner State.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        private void ReadResponseHeaders(InnerState innerState, HttpWebResponse response)
        {
            string header = response.GetResponseHeader("Content-Disposition");
            if (header != null)
            {
                innerState.HeaderContentDisposition = header;
            }

            header = response.GetResponseHeader("Content-Location");
            if (header != null)
            {
                innerState.HeaderContentLocation = header;
            }

            header = response.GetResponseHeader("ETag");
            if (header != null)
            {
                innerState.HeaderETag = header;
            }

            header = response.GetResponseHeader("Content-Type");
            if (header != null && header != "application/vnd.android.obb")
            {
                throw new StopRequestException(
                    ExpansionDownloadStatus.FileDeliveredIncorrectly, "file delivered with incorrect Mime type");
            }

            string headerTransferEncoding = response.GetResponseHeader("Transfer-Encoding");

            // todo - there seems to be no similar thing in .NET
            // if (!string.IsNullOrEmpty(headerTransferEncoding))
            // {
            header = response.GetResponseHeader("Content-Length");
            if (header != null)
            {
                innerState.HeaderContentLength = header;

                // this is always set from Market
                long contentLength = long.Parse(innerState.HeaderContentLength);
                if (contentLength != -1 && contentLength != this.downloadInfo.TotalBytes)
                {
                    // we're most likely on a bad wifi connection -- we should probably
                    // also look at the mime type --- but the size mismatch is enough
                    // to tell us that something is wrong here
                    Debug.WriteLine("LVLDL Incorrect file size delivered.");
                }
            }

            // }
            // else
            // {
            // // Ignore content-length with transfer-encoding - 2616 4.4 3
            // System.Diagnostics.Debug.WriteLine("DownloadThread : ignoring content-length because of xfer-encoding");
            // }
            Debug.WriteLine("DownloadThread : Content-Disposition: " + innerState.HeaderContentDisposition);
            Debug.WriteLine("DownloadThread : Content-Length: " + innerState.HeaderContentLength);
            Debug.WriteLine("DownloadThread : Content-Location: " + innerState.HeaderContentLocation);
            Debug.WriteLine("DownloadThread : ETag: " + innerState.HeaderETag);
            Debug.WriteLine("DownloadThread : Transfer-Encoding: " + headerTransferEncoding);

            bool noSizeInfo = innerState.HeaderContentLength == null
                              &&
                              (headerTransferEncoding == null
                               || !"chunked".Equals(headerTransferEncoding, StringComparison.OrdinalIgnoreCase));
            if (noSizeInfo)
            {
                throw new StopRequestException(ExpansionDownloadStatus.HttpDataError, "can't know size of download, giving up");
            }
        }
Exemplo n.º 19
0
        private static void print_log_oa1(HttpWebResponse response)
        {
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, System.Text.Encoding.GetEncoding(-0));

            string content = response.GetResponseHeader("Set-Cookie");
            session_id = content.Substring(content.IndexOf("JSESSIONID=") + "JSESSIONID=".Length, 32);

            string content_length = response.GetResponseHeader("Content-Length");
            if (content_length == "")
            {
                streamResponse.Close();
                streamRead.Close();
                return;
            }
            if (Int32.Parse(content_length) <= 0)
            {
                streamResponse.Close();
                streamRead.Close();
                return;
            }

            Char[] readBuff = new Char[256];
            int count = streamRead.Read(readBuff, 0, 256);
            Console.WriteLine("The contents of the Html page are.......\n");
            while (count > 0)
            {
                String outputData = new String(readBuff, 0, count);
                Console.Write(outputData);
                count = streamRead.Read(readBuff, 0, 256);
            }
            Console.WriteLine();

            // Close the Stream object.
            streamResponse.Close();
            streamRead.Close();
        }
Exemplo n.º 20
0
        private static void print_log1(HttpWebResponse response)
        {
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, System.Text.Encoding.GetEncoding(-0));

            string content_length = response.GetResponseHeader("Content-Length");
            if (content_length == "")
            {
                streamResponse.Close();
                streamRead.Close();
                return;
            }
            if (Int32.Parse(content_length) <= 0)
            {
                streamResponse.Close();
                streamRead.Close();
                return;
            }

            string readBuff = streamRead.ReadLine();
            do
            {
                //Console.Write(readBuff);
                //Console.WriteLine();
                search_ip(readBuff);
                readBuff = streamRead.ReadLine();
            } while (!streamRead.EndOfStream);

            // Close the Stream object.
            streamResponse.Close();
            streamRead.Close();
        }
Exemplo n.º 21
0
		private string ReadWebResponseAndStore(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service, string storePath) {

			using (Stream stream = webResponse.GetResponseStream()) {
				SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");

				int lengthContent = -1;
				if (webResponse.GetResponseHeader ("Content-Length") != null && webResponse.GetResponseHeader ("Content-Length") != "") {
					lengthContent = Int32.Parse (webResponse.GetResponseHeader ("Content-Length"));
				}
				// testing log line
				// SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
				int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
				if (lengthContent >= 0 && lengthContent<=bufferReadSize) {
					bufferReadSize = lengthContent;
				}
				SystemLogger.Log (SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
				string fullStorePath = Path.Combine(this.GetDirectoryRoot (), storePath);
				SystemLogger.Log (SystemLogger.Module.CORE, "storing file at: " + fullStorePath);
				FileStream streamWriter = new FileStream (fullStorePath, FileMode.Create);

				byte[] readBuffer = new byte[bufferReadSize];
				int readLen = 0;
				int totalRead = 0;
				do {
					readLen = stream.Read (readBuffer, 0, readBuffer.Length);
					streamWriter.Write (readBuffer, 0, readLen);
					totalRead = totalRead + readLen;
				} while (readLen >0);


				SystemLogger.Log (SystemLogger.Module.CORE, "total bytes: " + totalRead);
				streamWriter.Close ();
				streamWriter = null;

				return storePath;
			}
		}
Exemplo n.º 22
0
        public string GetWebServiceData(string url)
        {
            lock (this)
            {
                request = HttpWebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                string responseText = null;

                try
                {
                    response = request.GetResponse() as HttpWebResponse;

                    if (request.HaveResponse == true && response == null)
                    {
                        String msg = "response was not returned or is null";
                        throw new WebException(msg);
                    }

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
                        throw new WebException(msg);
                    }

                    // check response headers for the content type
                    string contentType = response.GetResponseHeader("Content-Type");

                    // get the response content
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseText = reader.ReadToEnd();
                    reader.Close();
                    reader.Dispose();

                    // handle failures
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        System.Console.Write(response.StatusCode + " " + response.StatusDescription);
                        response = (HttpWebResponse)e.Response;
                    }
                    else
                    {
                        System.Console.Write(e.Message);
                    }

                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }

                return responseText;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Gets the CoAP response from an incoming HTTP response. No null value is
	    /// returned. The response is created from a predefined mapping of the HTTP
        /// response codes. If the code is 204, which has
	    /// multiple meaning, the mapping is handled looking on the request method
	    /// that has originated the response. The options are set thorugh the HTTP
	    /// headers and the option max-age, if not indicated, is set to the default
	    /// value (60 seconds). if the response has an enclosing entity, it is mapped
	    /// to a CoAP payload and the content-type of the CoAP message is set
        /// properly.
        /// </summary>
        /// <param name="httpResponse">the http response</param>
        /// <param name="coapRequest">the coap response</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="TranslationException"></exception>
        public static Response GetCoapResponse(HttpWebResponse httpResponse, Request coapRequest)
        {
            if (httpResponse == null)
                throw ThrowHelper.ArgumentNull("httpResponse");
            if (coapRequest == null)
                throw ThrowHelper.ArgumentNull("coapRequest");

            HttpStatusCode httpCode = httpResponse.StatusCode;
            StatusCode coapCode = 0;

            // the code 204-"no content" should be managed
            // separately because it can be mapped to different coap codes
            // depending on the request that has originated the response
            if (httpCode == HttpStatusCode.NoContent)
            {
                if (coapRequest.Method == Method.DELETE)
                    coapCode = StatusCode.Deleted;
                else
                    coapCode = StatusCode.Changed;
            }
            else
            {
                if (!http2coapCode.TryGetValue(httpCode, out coapCode))
                    throw ThrowHelper.TranslationException("Cannot convert the HTTP status " + httpCode);
            }

            // create the coap reaponse
            Response coapResponse = new Response(coapCode);

            // translate the http headers in coap options
            IEnumerable<Option> coapOptions = GetCoapOptions(httpResponse.Headers);
            coapResponse.SetOptions(coapOptions);

            // the response should indicate a max-age value (CoAP 10.1.1)
            if (!coapResponse.HasOption(OptionType.MaxAge))
            {
                // The Max-Age Option for responses to POST, PUT or DELETE requests
                // should always be set to 0 (draft-castellani-core-http-mapping).
                coapResponse.MaxAge = coapRequest.Method == Method.GET ? CoapConstants.DefaultMaxAge : 0;
            }

            Byte[] buffer = new Byte[4096];
            using (Stream ms = new MemoryStream(buffer.Length), dataStream = httpResponse.GetResponseStream())
            {
                Int32 read;
                while ((read = dataStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                Byte[] payload = ((MemoryStream)ms).ToArray();
                if (payload.Length > 0)
                {
                    coapResponse.Payload = payload;
                    coapResponse.ContentType = GetCoapMediaType(httpResponse.GetResponseHeader("content-type"));
                }
            }

            return coapResponse;
        }
 public static string GetStringHeader(HttpWebResponse response, string headerName)
 {
     string headerValue = response.GetResponseHeader(headerName);
     if (headerValue != null)
         return headerValue;
     else
         return String.Empty;
 }
Exemplo n.º 25
0
        private APIResponse GetResponse(HttpWebResponse webResponse)
        {
            APIResponse response = new APIResponse();

            try
            {
                if (webResponse.GetResponseHeader("Set-Cookie").Length > 0)
                {
                    this.sessionCookie = webResponse.GetResponseHeader("Set-Cookie");
                }
                response.Code = webResponse.StatusCode;
                Stream responseStream = webResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream);
                response.ResponseData = streamReader.ReadToEnd();
                streamReader.Close();
                webResponse.Close();
            }
            catch (WebException exception)
            {
                response.Code = HttpStatusCode.BadRequest;
                response.ResponseData = exception.Message;
            }
            catch (Exception exception)
            {
                response.Code = HttpStatusCode.InternalServerError;
                response.ResponseData = exception.Message;
            }
            return response;
        }
Exemplo n.º 26
0
        internal static string Write(Options options, RunResult result, HttpWebResponse response)
        {
            var output = new StringBuilder();
            var oldColor = Console.ForegroundColor;
            
            if (result.ResponseCode != 0 && response == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                var line = string.Format("ERROR {0} {1} ",
                              options.Item.Url,
                              result.ResponseCode
                    );
                output.Append(line);
                Console.Write(line);
            }

            if (response != null)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                var line = string.Format("{0}/{1} {2} ",
                              (response.ResponseUri.OriginalString.ToLower().Contains("https") ? Consts.HTTPS : Consts.HTTP),
                              response.ProtocolVersion,
                              result.ResponseCode
                    );

                Console.Write(line);
                output.Append(line);

                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine(response.StatusDescription);
                output.Append(response.StatusDescription + Environment.NewLine);

                if (options.ShowHeaders)
                {
                    foreach (string header in response.Headers)
                    {
                        output.Append(WriteColored(header, response.GetResponseHeader(header)));
                    }
                }

                if (options.ShowBody)
                {
                    if (response.ContentType == "application/json")
                    {
                        var obj = JObject.Parse(result.ResponseBody);

                        output.Append(WriteJsonTree(obj, 1));
                    }
                    else
                    {
                        Console.ForegroundColor = oldColor;
                        output.Append(result.ResponseBody + Environment.NewLine);
                        Console.WriteLine(result.ResponseBody);
                    }
                }
            }

            Console.ForegroundColor = oldColor;

            return output.ToString();
        }