示例#1
0
            public override void Run()
            {
                HttpClient   httpclient = new DefaultHttpClient();
                HttpResponse response;
                string       responseString = null;

                try
                {
                    HttpPut      post = new HttpPut(pathToDoc1.ToExternalForm());
                    StringEntity se   = new StringEntity(docJson.ToString());
                    se.SetContentType(new BasicHeader("content_type", "application/json"));
                    post.SetEntity(se);
                    response = httpclient.Execute(post);
                    StatusLine statusLine = response.GetStatusLine();
                    Log.D(Test7_PullReplication.Tag, "Got response: " + statusLine);
                    NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated);
                }
                catch (ClientProtocolException e)
                {
                    NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
                                                      (), e);
                }
                catch (IOException e)
                {
                    NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
                }
                httpRequestDoneSignal.CountDown();
            }
            public override void Run()
            {
                HttpClient   httpclient = new DefaultHttpClient();
                HttpResponse response;
                string       responseString = null;

                try
                {
                    response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
                    StatusLine statusLine = response.GetStatusLine();
                    Log.D(ReplicationTest.Tag, "statusLine " + statusLine);
                    NUnit.Framework.Assert.AreEqual(HttpStatus.ScNotFound, statusLine.GetStatusCode()
                                                    );
                }
                catch (ClientProtocolException e)
                {
                    NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
                                                      (), e);
                }
                catch (IOException e)
                {
                    NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
                }
                finally
                {
                    httpRequestDoneSignal.CountDown();
                }
            }
示例#3
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Sharpen.URISyntaxException"/>
        private static int HttpNotification(string uri, int timeout)
        {
            DefaultHttpClient client = new DefaultHttpClient();

            client.GetParams().SetIntParameter(CoreConnectionPNames.SoTimeout, timeout).SetLongParameter
                (ClientPNames.ConnManagerTimeout, (long)timeout);
            HttpGet httpGet = new HttpGet(new URI(uri));

            httpGet.SetHeader("Accept", "*/*");
            return(client.Execute(httpGet).GetStatusLine().GetStatusCode());
        }
        public string GetJson(string url)
        {
            StringBuilder build    = new StringBuilder();
            IHttpClient   client   = new DefaultHttpClient();
            HttpGet       httpGet  = new HttpGet(url);
            IHttpResponse response = client.Execute(httpGet);
            IHttpEntity   entity   = response.Entity;

            System.IO.Stream content = entity.Content;
            BufferedReader   reader  = new BufferedReader(new InputStreamReader(content));
            string           con;

            while ((con = reader.ReadLine()) != null)
            {
                build.Append(con);
            }
            return(build.ToString());
        }
            public override void Run()
            {
                HttpClient   httpclient = new DefaultHttpClient();
                HttpResponse response;
                string       responseString = null;

                try
                {
                    response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
                    StatusLine statusLine = response.GetStatusLine();
                    NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
                    if (statusLine.GetStatusCode() == HttpStatus.ScOk)
                    {
                        ByteArrayOutputStream @out = new ByteArrayOutputStream();
                        response.GetEntity().WriteTo(@out);
                        @out.Close();
                        responseString = @out.ToString();
                        NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
                        Log.D(ReplicationTest.Tag, "result: " + responseString);
                    }
                    else
                    {
                        response.GetEntity().GetContent().Close();
                        throw new IOException(statusLine.GetReasonPhrase());
                    }
                }
                catch (ClientProtocolException e)
                {
                    NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
                                                      (), e);
                }
                catch (IOException e)
                {
                    NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
                }
                httpRequestDoneSignal.CountDown();
            }
示例#6
0
        public T HttpGet <T>()
        {
            T      result      = default(T);
            string webResponse = string.Empty;

            try
            {
                if ((int)Android.OS.Build.VERSION.SdkInt > 9)
                {
                    Android.OS.StrictMode.ThreadPolicy policy = new Android.OS.StrictMode.ThreadPolicy.Builder().PermitAll().Build();
                    Android.OS.StrictMode.SetThreadPolicy(policy);
                }
                using (var httpclient = new DefaultHttpClient())
                {
                    using (var request = new HttpGet())
                    {
                        request.URI = new Java.Net.URI(Url + GetParams());
                        using (var response = httpclient.Execute(request))
                        {
                            webResponse = StreamToString(response.Entity.Content).Replace("https:", "http:").ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                webResponse = string.Empty;
            }

            if (string.IsNullOrEmpty(webResponse))
            {
                webResponse = "{}";
            }

            result = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(webResponse);
            return(result);
        }
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					HttpPut post = new HttpPut(pathToDoc1.ToExternalForm());
					StringEntity se = new StringEntity(docJson.ToString());
					se.SetContentType(new BasicHeader("content_type", "application/json"));
					post.SetEntity(se);
					response = httpclient.Execute(post);
					StatusLine statusLine = response.GetStatusLine();
					Log.D(ReplicationTest.Tag, "Got response: " + statusLine);
					NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated);
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				httpRequestDoneSignal.CountDown();
			}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
					StatusLine statusLine = response.GetStatusLine();
					Log.D(ReplicationTest.Tag, "statusLine " + statusLine);
					NUnit.Framework.Assert.AreEqual(HttpStatus.ScNotFound, statusLine.GetStatusCode()
						);
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				finally
				{
					httpRequestDoneSignal.CountDown();
				}
			}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
					StatusLine statusLine = response.GetStatusLine();
					NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
					if (statusLine.GetStatusCode() == HttpStatus.ScOk)
					{
						ByteArrayOutputStream @out = new ByteArrayOutputStream();
						response.GetEntity().WriteTo(@out);
						@out.Close();
						responseString = @out.ToString();
						NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
						Log.D(ReplicationTest.Tag, "result: " + responseString);
					}
					else
					{
						response.GetEntity().GetContent().Close();
						throw new IOException(statusLine.GetReasonPhrase());
					}
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				httpRequestDoneSignal.CountDown();
			}
示例#10
0
        /// <summary>Download link and have it be the response.</summary>
        /// <param name="req">the http request</param>
        /// <param name="resp">the http response</param>
        /// <param name="link">the link to download</param>
        /// <param name="c">the cookie to set if any</param>
        /// <exception cref="System.IO.IOException">on any error.</exception>
        private static void ProxyLink(HttpServletRequest req, HttpServletResponse resp, URI
                                      link, Cookie c, string proxyHost)
        {
            DefaultHttpClient client = new DefaultHttpClient();

            client.GetParams().SetParameter(ClientPNames.CookiePolicy, CookiePolicy.BrowserCompatibility
                                            ).SetBooleanParameter(ClientPNames.AllowCircularRedirects, true);
            // Make sure we send the request from the proxy address in the config
            // since that is what the AM filter checks against. IP aliasing or
            // similar could cause issues otherwise.
            IPAddress localAddress = Sharpen.Extensions.GetAddressByName(proxyHost);

            if (Log.IsDebugEnabled())
            {
                Log.Debug("local InetAddress for proxy host: {}", localAddress);
            }
            client.GetParams().SetParameter(ConnRoutePNames.LocalAddress, localAddress);
            HttpGet httpGet            = new HttpGet(link);
            Enumeration <string> names = req.GetHeaderNames();

            while (names.MoveNext())
            {
                string name = names.Current;
                if (passThroughHeaders.Contains(name))
                {
                    string value = req.GetHeader(name);
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("REQ HEADER: {} : {}", name, value);
                    }
                    httpGet.SetHeader(name, value);
                }
            }
            string user = req.GetRemoteUser();

            if (user != null && !user.IsEmpty())
            {
                httpGet.SetHeader("Cookie", ProxyUserCookieName + "=" + URLEncoder.Encode(user, "ASCII"
                                                                                          ));
            }
            OutputStream @out = resp.GetOutputStream();

            try
            {
                HttpResponse httpResp = client.Execute(httpGet);
                resp.SetStatus(httpResp.GetStatusLine().GetStatusCode());
                foreach (Header header in httpResp.GetAllHeaders())
                {
                    resp.SetHeader(header.GetName(), header.GetValue());
                }
                if (c != null)
                {
                    resp.AddCookie(c);
                }
                InputStream @in = httpResp.GetEntity().GetContent();
                if (@in != null)
                {
                    IOUtils.CopyBytes(@in, @out, 4096, true);
                }
            }
            finally
            {
                httpGet.ReleaseConnection();
            }
        }
示例#11
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.MyButton);

            button.Click += delegate
            {
                //记住打开权限

                //String path = "http://localhost:8733/WcfService/Service1/AddUser";
                //// 新建一个URL对象
                //URL url = new URL(path);
                //// 打开一个HttpURLConnection连接
                //HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection();
                //// 设置连接超时时间
                //urlConn.ConnectTimeout = 5*1000;
                //// 开始连接
                //urlConn.Connect();
                //// 判断请求是否成功
                //if (urlConn.ResponseCode==HttpStatus.Ok)
                //{
                //    // 获取返回的数据

                //}
                //else {
                //    Log.Info("OnCreate", "Get方式请求失败");
                //}
                //// 关闭连接
                //urlConn.Disconnect();



                //Uri uri =new Uri("http://localhost:8733/WcfService/Service1/AddUser");
                //Intent it = new Intent(Intent.ActionView, uri);
                //StartActivity(it);


                //访问百度的html文件的源码
                //URL url = new URL("http://www.baidu.com/");
                //HttpURLConnection urlConnection = (HttpURLConnection)url.OpenConnection();

                //try
                //{
                //    InputStream inputStream = new BufferedInputStream(urlConnection.InputStream);
                //}
                //finally

                //{
                //    urlConnection.Disconnect();
                //}

                // Creating HTTP client
                DefaultHttpClient httpClient = new DefaultHttpClient();

                // Creating HTTP Post
                HttpPost httpPost = new HttpPost("http://localhost:8733/WcfService/Service1/AddUser/1/1/1/1");
                //httpPost.Entity=new BasicHttpEntity();
                // Making HTTP Request
                try
                {
                    IHttpResponse response = httpClient.Execute(httpPost);

                    // writing response to log
                    Log.Debug("Http Response:", response.ToString());
                }
                catch (Exception e)
                {
                }
            };
        }
 /// <exception cref="System.UriFormatException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 private HttpResponse GetRemoteDoc(Uri pathToDoc)
 {
     HttpClient httpclient = new DefaultHttpClient();
     HttpResponse response = null;
     string responseString = null;
     response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
     StatusLine statusLine = response.GetStatusLine();
     if (statusLine.GetStatusCode() != HttpStatus.ScOk)
     {
         throw new RuntimeException("Did not get 200 status doing GET to URL: " + pathToDoc
             );
     }
     return response;
 }
 /// <exception cref="System.Exception"></exception>
 public virtual void TestRemoteConflictResolution()
 {
     // Create a document with two conflicting edits.
     Document doc = database.CreateDocument();
     SavedRevision rev1 = doc.CreateRevision().Save();
     SavedRevision rev2a = CreateRevisionWithRandomProps(rev1, false);
     SavedRevision rev2b = CreateRevisionWithRandomProps(rev1, true);
     // make sure we can query the db to get the conflict
     Query allDocsQuery = database.CreateAllDocumentsQuery();
     allDocsQuery.SetAllDocsMode(Query.AllDocsMode.OnlyConflicts);
     QueryEnumerator rows = allDocsQuery.Run();
     bool foundDoc = false;
     NUnit.Framework.Assert.AreEqual(1, rows.GetCount());
     for (IEnumerator<QueryRow> it = rows; it.HasNext(); )
     {
         QueryRow row = it.Next();
         if (row.GetDocument().GetId().Equals(doc.GetId()))
         {
             foundDoc = true;
         }
     }
     NUnit.Framework.Assert.IsTrue(foundDoc);
     // Push the conflicts to the remote DB.
     Replication push = database.CreatePushReplication(GetReplicationURL());
     RunReplication(push);
     NUnit.Framework.Assert.IsNull(push.GetLastError());
     // Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
     JSONObject rev3aBody = new JSONObject();
     rev3aBody.Put("_id", doc.GetId());
     rev3aBody.Put("_rev", rev2a.GetId());
     // Then, delete rev 2b.
     JSONObject rev3bBody = new JSONObject();
     rev3bBody.Put("_id", doc.GetId());
     rev3bBody.Put("_rev", rev2b.GetId());
     rev3bBody.Put("_deleted", true);
     // Combine into one _bulk_docs request.
     JSONObject requestBody = new JSONObject();
     requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
     // Make the _bulk_docs request.
     HttpClient client = new DefaultHttpClient();
     string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
     HttpPost request = new HttpPost(bulkDocsUrl);
     request.SetHeader("Content-Type", "application/json");
     string json = requestBody.ToString();
     request.SetEntity(new StringEntity(json));
     HttpResponse response = client.Execute(request);
     // Check the response to make sure everything worked as it should.
     NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
     string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
     JSONArray resultArray = new JSONArray(rawResponse);
     NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
     for (int i = 0; i < resultArray.Length(); i++)
     {
         NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
     }
     WorkaroundSyncGatewayRaceCondition();
     // Pull the remote changes.
     Replication pull = database.CreatePullReplication(GetReplicationURL());
     RunReplication(pull);
     NUnit.Framework.Assert.IsNull(pull.GetLastError());
     // Make sure the conflict was resolved locally.
     NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
 }
示例#14
0
		/// <exception cref="System.Exception"></exception>
		public virtual void TestRemoteConflictResolution()
		{
			// Create a document with two conflicting edits.
			Document doc = database.CreateDocument();
			SavedRevision rev1 = doc.CreateRevision().Save();
			SavedRevision rev2a = rev1.CreateRevision().Save();
			SavedRevision rev2b = rev1.CreateRevision().Save(true);
			// Push the conflicts to the remote DB.
			Replication push = database.CreatePushReplication(GetReplicationURL());
			RunReplication(push);
			// Prepare a bulk docs request to resolve the conflict remotely. First, advance rev 2a.
			JSONObject rev3aBody = new JSONObject();
			rev3aBody.Put("_id", doc.GetId());
			rev3aBody.Put("_rev", rev2a.GetId());
			// Then, delete rev 2b.
			JSONObject rev3bBody = new JSONObject();
			rev3bBody.Put("_id", doc.GetId());
			rev3bBody.Put("_rev", rev2b.GetId());
			rev3bBody.Put("_deleted", true);
			// Combine into one _bulk_docs request.
			JSONObject requestBody = new JSONObject();
			requestBody.Put("docs", new JSONArray(Arrays.AsList(rev3aBody, rev3bBody)));
			// Make the _bulk_docs request.
			HttpClient client = new DefaultHttpClient();
			string bulkDocsUrl = GetReplicationURL().ToExternalForm() + "/_bulk_docs";
			HttpPost request = new HttpPost(bulkDocsUrl);
			request.SetHeader("Content-Type", "application/json");
			string json = requestBody.ToString();
			request.SetEntity(new StringEntity(json));
			HttpResponse response = client.Execute(request);
			// Check the response to make sure everything worked as it should.
			NUnit.Framework.Assert.AreEqual(201, response.GetStatusLine().GetStatusCode());
			string rawResponse = IOUtils.ToString(response.GetEntity().GetContent());
			JSONArray resultArray = new JSONArray(rawResponse);
			NUnit.Framework.Assert.AreEqual(2, resultArray.Length());
			for (int i = 0; i < resultArray.Length(); i++)
			{
				NUnit.Framework.Assert.IsTrue(((JSONObject)resultArray.Get(i)).IsNull("error"));
			}
			WorkaroundSyncGatewayRaceCondition();
			// Pull the remote changes.
			Replication pull = database.CreatePullReplication(GetReplicationURL());
			RunReplication(pull);
			// Make sure the conflict was resolved locally.
			NUnit.Framework.Assert.AreEqual(1, doc.GetConflictingRevisions().Count);
		}