コード例 #1
0
        /// <summary>Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers.
        ///     </summary>
        /// <remarks>Processes the response (possibly updating or inserting) Content-Length and Transfer-Encoding headers.
        ///     </remarks>
        /// <param name="response">The HttpResponse to modify.</param>
        /// <param name="context">Unused.</param>
        /// <exception cref="Org.Apache.Http.ProtocolException">If either the Content-Length or Transfer-Encoding headers are found.
        ///     </exception>
        /// <exception cref="System.ArgumentException">If the response is null.</exception>
        /// <exception cref="Org.Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(HttpResponse response, HttpContext context)
        {
            Args.NotNull(response, "HTTP response");
            if (this.overwrite)
            {
                response.RemoveHeaders(HTTP.TransferEncoding);
                response.RemoveHeaders(HTTP.ContentLen);
            }
            else
            {
                if (response.ContainsHeader(HTTP.TransferEncoding))
                {
                    throw new ProtocolException("Transfer-encoding header already present");
                }
                if (response.ContainsHeader(HTTP.ContentLen))
                {
                    throw new ProtocolException("Content-Length header already present");
                }
            }
            ProtocolVersion ver    = response.GetStatusLine().GetProtocolVersion();
            HttpEntity      entity = response.GetEntity();

            if (entity != null)
            {
                long len = entity.GetContentLength();
                if (entity.IsChunked() && !ver.LessEquals(HttpVersion.Http10))
                {
                    response.AddHeader(HTTP.TransferEncoding, HTTP.ChunkCoding);
                }
                else
                {
                    if (len >= 0)
                    {
                        response.AddHeader(HTTP.ContentLen, System.Convert.ToString(entity.GetContentLength
                                                                                        ()));
                    }
                }
                // Specify a content type if known
                if (entity.GetContentType() != null && !response.ContainsHeader(HTTP.ContentType))
                {
                    response.AddHeader(entity.GetContentType());
                }
                // Specify a content encoding if known
                if (entity.GetContentEncoding() != null && !response.ContainsHeader(HTTP.ContentEncoding
                                                                                    ))
                {
                    response.AddHeader(entity.GetContentEncoding());
                }
            }
            else
            {
                int status = response.GetStatusLine().GetStatusCode();
                if (status != HttpStatus.ScNoContent && status != HttpStatus.ScNotModified && status
                    != HttpStatus.ScResetContent)
                {
                    response.AddHeader(HTTP.ContentLen, "0");
                }
            }
        }
コード例 #2
0
 /// <exception cref="Org.Apache.Http.HttpException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual void Process(IHttpRequest request, HttpContext context)
 {
     Args.NotNull(request, "HTTP request");
     if (request is HttpEntityEnclosingRequest)
     {
         if (this.overwrite)
         {
             request.RemoveHeaders(HTTP.TransferEncoding);
             request.RemoveHeaders(HTTP.ContentLen);
         }
         else
         {
             if (request.ContainsHeader(HTTP.TransferEncoding))
             {
                 throw new ProtocolException("Transfer-encoding header already present");
             }
             if (request.ContainsHeader(HTTP.ContentLen))
             {
                 throw new ProtocolException("Content-Length header already present");
             }
         }
         ProtocolVersion ver    = request.GetRequestLine().GetProtocolVersion();
         HttpEntity      entity = ((HttpEntityEnclosingRequest)request).GetEntity();
         if (entity == null)
         {
             request.AddHeader(HTTP.ContentLen, "0");
             return;
         }
         // Must specify a transfer encoding or a content length
         if (entity.IsChunked() || entity.GetContentLength() < 0)
         {
             if (ver.LessEquals(HttpVersion.Http10))
             {
                 throw new ProtocolException("Chunked transfer encoding not allowed for " + ver);
             }
             request.AddHeader(HTTP.TransferEncoding, HTTP.ChunkCoding);
         }
         else
         {
             request.AddHeader(HTTP.ContentLen, System.Convert.ToString(entity.GetContentLength
                                                                            ()));
         }
         // Specify a content type if known
         if (entity.GetContentType() != null && !request.ContainsHeader(HTTP.ContentType))
         {
             request.AddHeader(entity.GetContentType());
         }
         // Specify a content encoding if known
         if (entity.GetContentEncoding() != null && !request.ContainsHeader(HTTP.ContentEncoding
                                                                            ))
         {
             request.AddHeader(entity.GetContentEncoding());
         }
     }
 }
コード例 #3
0
        /// <summary>Obtains MIME type of the entity, if known.</summary>
        /// <remarks>Obtains MIME type of the entity, if known.</remarks>
        /// <param name="entity">must not be null</param>
        /// <returns>the character set, or null if not found</returns>
        /// <exception cref="Org.Apache.Http.ParseException">if header elements cannot be parsed
        ///     </exception>
        /// <exception cref="System.ArgumentException">if entity is null</exception>
        /// <since>4.1</si        [System.ObsoleteAttribute(@"(4.1.3) use Org.Apache.Http.Entity.ContentType.GetOrDefault(Org.Apache.Http.HttpEntity)")]y)"

        public static string GetContentMimeType(HttpEntity entity)
        {
            Args.NotNull(entity, "Entity");
            string mimeType = null;

            if (entity.GetContentType() != null)
            {
                HeaderElement[] values = entity.GetContentType().GetElements();
                if (values.Length > 0)
                {
                    mimeType = values[0].GetName();
                }
            }
            return(mimeType);
        }
コード例 #4
0
        /// <summary>Obtains character set of the entity, if known.</summary>
        /// <remarks>Obtains character set of the entity, if known.</remarks>
        /// <param name="entity">must not be null</param>
        /// <returns>the character set, or null if not found</returns>
        /// <exception cref="Org.Apache.Http.ParseException">if header elements cannot be parsed
        ///     </exception>
        /// <exception cref="System.ArgumentException">if entity is null</exception>      [System.ObsoleteAttribute(@"(4.1.3) use Org.Apache.Http.Entity.ContentType.GetOrDefault(Org.Apache.Http.HttpEntity)")]
        public static string GetContentCharSet(HttpEntity entity)
        {
            Args.NotNull(entity, "Entity");
            string charset = null;

            if (entity.GetContentType() != null)
            {
                HeaderElement[] values = entity.GetContentType().GetElements();
                if (values.Length > 0)
                {
                    NameValuePair param = values[0].GetParameterByName("charset");
                    if (param != null)
                    {
                        charset = param.GetValue();
                    }
                }
            }
            return(charset);
        }
コード例 #5
0
        /// <summary>
        /// Extracts <code>Content-Type</code> value from
        /// <see cref="Org.Apache.Http.HttpEntity">Org.Apache.Http.HttpEntity</see>
        /// exactly as
        /// specified by the <code>Content-Type</code> header of the entity. Returns <code>null</code>
        /// if not specified.
        /// </summary>
        /// <param name="entity">HTTP entity</param>
        /// <returns>content type</returns>
        /// <exception cref="Org.Apache.Http.ParseException">
        /// if the given text does not represent a valid
        /// <code>Content-Type</code> value.
        /// </exception>
        /// <exception cref="Sharpen.UnsupportedCharsetException">
        /// Thrown when the named charset is not available in
        /// this instance of the Java virtual machine
        /// </exception>
        public static Org.Apache.Http.Entity.ContentType Get(HttpEntity entity)
        {
            if (entity == null)
            {
                return(null);
            }
            Header header = entity.GetContentType();

            if (header != null)
            {
                HeaderElement[] elements = header.GetElements();
                if (elements.Length > 0)
                {
                    return(Create(elements[0]));
                }
            }
            return(null);
        }
コード例 #6
0
        /// <summary>
        /// Returns true if the entity's Content-Type header is
        /// <code>application/x-www-form-urlencoded</code>.
        /// </summary>
        /// <remarks>
        /// Returns true if the entity's Content-Type header is
        /// <code>application/x-www-form-urlencoded</code>.
        /// </remarks>
        public static bool IsEncoded(HttpEntity entity)
        {
            Header h = entity.GetContentType();

            if (h != null)
            {
                HeaderElement[] elems = h.GetElements();
                if (elems.Length > 0)
                {
                    string contentType = elems[0].GetName();
                    return(Sharpen.Runtime.EqualsIgnoreCase(contentType, ContentType));
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #7
0
        protected internal override void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                        request)
        {
            object       fullBody = null;
            Exception    error    = null;
            HttpResponse response = null;

            try
            {
                if (request.IsAborted())
                {
                    RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted"
                                                                            , this, request)), response);
                    return;
                }
                response = httpClient.Execute(request);
                try
                {
                    // add in cookies to global store
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        clientFactory.AddCookies(defaultHttpClient.GetCookieStore().GetCookies());
                    }
                }
                catch (Exception e)
                {
                    Log.E(Log.TagRemoteRequest, "Unable to add in cookies to global store", e);
                }
                StatusLine status = response.GetStatusLine();
                if (status.GetStatusCode() >= 300)
                {
                    Log.E(Log.TagRemoteRequest, "Got error status: %d for %s.  Reason: %s", status.GetStatusCode
                              (), request, status.GetReasonPhrase());
                    error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase(
                                                          ));
                }
                else
                {
                    HttpEntity  entity            = response.GetEntity();
                    Header      contentTypeHeader = entity.GetContentType();
                    InputStream inputStream       = null;
                    if (contentTypeHeader != null && contentTypeHeader.GetValue().Contains("multipart/"
                                                                                           ))
                    {
                        Log.V(Log.TagSync, "contentTypeHeader = %s", contentTypeHeader.GetValue());
                        try
                        {
                            _topReader  = new MultipartReader(contentTypeHeader.GetValue(), this);
                            inputStream = entity.GetContent();
                            int    bufLen       = 1024;
                            byte[] buffer       = new byte[bufLen];
                            int    numBytesRead = 0;
                            while ((numBytesRead = inputStream.Read(buffer)) != -1)
                            {
                                if (numBytesRead != bufLen)
                                {
                                    byte[] bufferToAppend = Arrays.CopyOfRange(buffer, 0, numBytesRead);
                                    _topReader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    _topReader.AppendData(buffer);
                                }
                            }
                            _topReader.Finished();
                            RespondWithResult(fullBody, error, response);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        Log.V(Log.TagSync, "contentTypeHeader is not multipart = %s", contentTypeHeader.GetValue
                                  ());
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.GetContent();
                                fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Log.E(Log.TagRemoteRequest, "io exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
            catch (Exception e)
            {
                Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
        }
        protected internal override void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
                                                        request)
        {
            object    fullBody = null;
            Exception error    = null;

            try
            {
                HttpResponse response = httpClient.Execute(request);
                try
                {
                    // add in cookies to global store
                    if (httpClient is DefaultHttpClient)
                    {
                        DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                        CouchbaseLiteHttpClientFactory.Instance.AddCookies(defaultHttpClient.GetCookieStore
                                                                               ().GetCookies());
                    }
                }
                catch (Exception e)
                {
                    Log.E(Database.Tag, "Unable to add in cookies to global store", e);
                }
                StatusLine status = response.GetStatusLine();
                if (status.GetStatusCode() >= 300)
                {
                    Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode
                                                                                       ()));
                    Log.E(Database.Tag, "Request was for: " + request.ToString());
                    Log.E(Database.Tag, "Status reason: " + status.GetReasonPhrase());
                    error = new HttpResponseException(status.GetStatusCode(), status.GetReasonPhrase(
                                                          ));
                }
                else
                {
                    HttpEntity  entity            = response.GetEntity();
                    Header      contentTypeHeader = entity.GetContentType();
                    InputStream inputStream       = null;
                    if (contentTypeHeader != null && contentTypeHeader.GetValue().Contains("multipart/related"
                                                                                           ))
                    {
                        try
                        {
                            MultipartDocumentReader reader = new MultipartDocumentReader(response, db);
                            reader.SetContentType(contentTypeHeader.GetValue());
                            inputStream = entity.GetContent();
                            int    bufLen       = 1024;
                            byte[] buffer       = new byte[bufLen];
                            int    numBytesRead = 0;
                            while ((numBytesRead = inputStream.Read(buffer)) != -1)
                            {
                                if (numBytesRead != bufLen)
                                {
                                    byte[] bufferToAppend = Arrays.CopyOfRange(buffer, 0, numBytesRead);
                                    reader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    reader.AppendData(buffer);
                                }
                            }
                            reader.Finish();
                            fullBody = reader.GetDocumentProperties();
                            RespondWithResult(fullBody, error);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.GetContent();
                                fullBody    = Manager.GetObjectMapper().ReadValue <object>(inputStream);
                                RespondWithResult(fullBody, error);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (ClientProtocolException e)
            {
                Log.E(Database.Tag, "client protocol exception", e);
                error = e;
            }
            catch (IOException e)
            {
                Log.E(Database.Tag, "io exception", e);
                error = e;
            }
        }
コード例 #9
0
 public virtual Header GetContentType()
 {
     return(wrappedEntity.GetContentType());
 }