Ejemplo n.º 1
0
        internal void SendAsyncRequest(HttpMethod method, Uri url, Object body, RemoteRequestCompletionBlock completionHandler)
        {
            var message = new HttpRequestMessage(method, url);
            var mapper  = Manager.GetObjectMapper();

            if (body != null)
            {
                var bytes       = mapper.WriteValueAsBytes(body).ToArray();
                var byteContent = new ByteArrayContent(bytes);
                message.Content = byteContent;
            }
            message.Headers.Add("Accept", new[] { "multipart/related", "application/json" });

            PreemptivelySetAuthCredentials(message);

            var client = clientFactory.GetHttpClient();

            client.CancelPendingRequests();
            client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, CancellationTokenSource.Token)
            .ContinueWith(response => {
                if (response.Status != TaskStatus.RanToCompletion)
                {
                    Log.E(Tag, "SendAsyncRequest did not run to completion.", response.Exception);
                    return(null);
                }
                return(response.Result);
            }, CancellationTokenSource.Token)
            .ContinueWith(response => {
                if (completionHandler != null)
                {
                    var fullBody = mapper.ReadValue <Object>(response.Result.Content.ReadAsStreamAsync().Result);

                    Exception error = response.Exception;
                    if (error == null && !response.Result.IsSuccessStatusCode)
                    {
                        error = new HttpResponseException(response.Result.StatusCode);
                    }

                    completionHandler(fullBody, response.Exception);
                }
            });
        }
 protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
      request)
 {
     object fullBody = null;
     Exception error = null;
     HttpResponse response = null;
     try
     {
         Log.V(Log.TagSync, "%s: RemoteRequest executeRequest() called, url: %s", this, url
             );
         if (request.IsAborted())
         {
             Log.V(Log.TagSync, "%s: RemoteRequest has already been aborted", this);
             RespondWithResult(fullBody, new Exception(string.Format("%s: Request %s has been aborted"
                 , this, request)), response);
             return;
         }
         Log.V(Log.TagSync, "%s: RemoteRequest calling httpClient.execute", this);
         response = httpClient.Execute(request);
         Log.V(Log.TagSync, "%s: RemoteRequest called httpClient.execute", this);
         // add in cookies to global store
         try
         {
             if (httpClient is DefaultHttpClient)
             {
                 DefaultHttpClient defaultHttpClient = (DefaultHttpClient)httpClient;
                 this.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 (Utils.IsTransientError(status) && RetryRequest())
         {
             return;
         }
         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 temp = response.GetEntity();
             if (temp != null)
             {
                 InputStream stream = null;
                 try
                 {
                     stream = temp.GetContent();
                     fullBody = Manager.GetObjectMapper().ReadValue<object>(stream);
                 }
                 finally
                 {
                     try
                     {
                         stream.Close();
                     }
                     catch (IOException)
                     {
                     }
                 }
             }
         }
     }
     catch (IOException e)
     {
         Log.E(Log.TagRemoteRequest, "io exception", e);
         error = e;
         // Treat all IOExceptions as transient, per:
         // http://hc.apache.org/httpclient-3.x/exception-handling.html
         Log.V(Log.TagSync, "%s: RemoteRequest calling retryRequest()", this);
         if (RetryRequest())
         {
             return;
         }
     }
     catch (Exception e)
     {
         Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
         error = e;
     }
     Log.V(Log.TagSync, "%s: RemoteRequest calling respondWithResult.  error: %s", this
         , error);
     RespondWithResult(fullBody, error, response);
 }
 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;
                 this.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/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, response);
                 }
                 finally
                 {
                     try
                     {
                         inputStream.Close();
                     }
                     catch (IOException)
                     {
                     }
                 }
             }
             else
             {
                 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, "%s: io exception", e, this);
         error = e;
         RespondWithResult(fullBody, e, response);
     }
     catch (Exception e)
     {
         Log.E(Log.TagRemoteRequest, "%s: executeRequest() Exception: ", e, this);
         error = e;
         RespondWithResult(fullBody, e, response);
     }
     finally
     {
         Log.E(Log.TagRemoteRequest, "%s: executeRequest() finally", this);
     }
 }
Ejemplo n.º 4
0
		protected internal virtual void ExecuteRequest(HttpClient httpClient, HttpRequestMessage
			 request)
		{
			object fullBody = null;
			Exception error = null;
			try
			{
				HttpResponse response = httpClient.Execute(request);
				// add in cookies to global store
				try
				{
					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 temp = response.GetEntity();
					if (temp != null)
					{
						InputStream stream = null;
						try
						{
							stream = temp.GetContent();
							fullBody = Manager.GetObjectMapper().ReadValue<object>(stream);
						}
						finally
						{
							try
							{
								stream.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;
			}
			RespondWithResult(fullBody, error);
		}
		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;
			}
		}