Example #1
0
 public void sendData(string url)
 {
     /*
      * var request = HttpWebRequest.Create(url);
      * var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
      */
     try
     {
         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
         myRequest.Method      = "POST";
         myRequest.ContentType = "application/x-www-form-urlencoded";
         myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
     }
     catch (Exception e)
     {
     }
 }
Example #2
0
        public static Stream GetRequestStream(HttpWebRequest request)
        {
            var    dataReady = new AutoResetEvent(false);
            Stream stream    = null;
            var    callback  = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
            {
                stream = (Stream)request.EndGetRequestStream(asynchronousResult);
                dataReady.Set();
            });

            request.BeginGetRequestStream(callback, request);
            if (!dataReady.WaitOne(10000))
            {
                return(null);
            }
            return(stream);
        }
Example #3
0
        public HttpWebRequest UploadDataAsync(Uri address, byte[] data, RequestCompletedEventHandler completedCallback)
        {
            HttpWebRequest request = SetupRequest(address);

            if (AuthorizationToken != null)
            {
                request.Headers[HttpRequestHeader.Authorization] = String.Format("GoogleLogin auth={0}", AuthorizationToken);
            }


            request.Method = "POST";

            RequestState state  = new RequestState(request, data, completedCallback);
            IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);

            return(request);
        }
Example #4
0
        private void PostAnswer()
        {
            // Est-ce que la quote a été incluse ?
            if (showQuoteButton.Visibility == System.Windows.Visibility.Visible && action == "quote")
            {
                string answerSave = answerTextBox.Text;
                answerTextBox.Text = quotedText + answerSave;
            }
            // Désactivation des bouton de post et de la textbox
            ApplicationBar.IsVisible = false;
            answerTextBox.IsEnabled  = false;

            // Affichage de la ProgressBar
            SystemTray.ProgressIndicator.IsVisible       = true;
            SystemTray.ProgressIndicator.IsIndeterminate = true;
            SystemTray.ProgressIndicator.Text            = "Envoi de votre réponse...";

            // Réponse
            answer = Regex.Replace(answerTextBox.Text, "\r\n", "\r");
            answer = Regex.Replace(answer, "\r", Environment.NewLine);
            answer = HttpUtility.UrlEncode(answer);
            //answer = Regex.Replace(HttpUtility.HtmlEncode(answer), "%250D%250A", "%0D%0A");


            // Création de l'objet HttpWebRequest.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://forum.hardware.fr/bddpost.php");

            // ContentType
            request.ContentType = "application/x-www-form-urlencoded";

            //Cookie
            request.CookieContainer = container;

            // Méthode en POST
            request.Method = "POST";

            // Ligne spécifique à SFR : headers EXPECT 100 CONTINUE
            request.Headers["User-Agent"] = "Mozilla /4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; IEMobile/7.0) Vodafone/1.0/SFR_v1615/1.56.163.8.39";

            try
            {
                // Démarrage de l'opération asynchrone
                request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            }
            catch { MessageBox.Show("Erreur de connectivité. Veuillez réessayer"); }
        }
Example #5
0
 public static void Upload(string uri, Stream data, string paramName, string uploadContentType, Action <JsonResponseData> resultCallback, string fileName = null, Action <double> progressCallback = null, Cancellation c = null)
 {
     JsonWebRequest.RequestState rState = new JsonWebRequest.RequestState()
     {
         resultCallback = resultCallback
     };
     try
     {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
         request.AllowWriteStreamBuffering = false;
         request.UserAgent = AppInfo.AppVersionForUserAgent;
         rState.request    = request;
         request.Method    = "POST";
         string str1 = string.Format("----------{0:N}", Guid.NewGuid());
         string str2 = "multipart/form-data; boundary=" + str1;
         request.ContentType     = str2;
         request.CookieContainer = new CookieContainer();
         string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", str1, paramName, (fileName ?? "myDataFile"), uploadContentType);
         string footer = string.Format("\r\n--{0}--\r\n", str1);
         request.ContentLength = ((long)Encoding.UTF8.GetByteCount(header) + data.Length + (long)Encoding.UTF8.GetByteCount(footer));
         request.BeginGetRequestStream((AsyncCallback)(ar =>
         {
             try
             {
                 Stream requestStream = request.EndGetRequestStream(ar);
                 requestStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));
                 StreamUtils.CopyStream(data, requestStream, progressCallback, c, 0L);
                 requestStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
                 requestStream.Close();
                 request.BeginGetResponse(new AsyncCallback(JsonWebRequest.RespCallback), rState);
             }
             catch (Exception ex)
             {
                 Logger.Instance.Error("Upload failed to write data to request stream.", ex);
                 JsonWebRequest.SafeClose(rState);
                 JsonWebRequest.SafeInvokeCallback(rState.resultCallback, false, null);
             }
         }), null);
     }
     catch (Exception ex)
     {
         Logger.Instance.Error("Upload failed.", ex);
         JsonWebRequest.SafeClose(rState);
         JsonWebRequest.SafeInvokeCallback(rState.resultCallback, false, null);
     }
 }
Example #6
0
        void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            string userToken = readUserToken();

            if (!String.IsNullOrEmpty(userToken))
            {
                HttpWebRequest req = HttpWebRequest.Create(new Uri(BASE + "/account/device")) as HttpWebRequest;
                req.Headers["Cookie"] = "user="******"POST";
                req.ContentType       = "application/json";
                req.BeginGetRequestStream(setParams_Callback, new object[] { req, e.ChannelUri.ToString() });
            }
            else
            {
                NotifyComplete();
            }
        }
Example #7
0
 private static void doPostAsync(String url)
 {
     try
     {
         HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
         req.Method      = "POST";
         req.ContentType = "application/x-www-form-urlencoded; charset=utf-8 ";
         System.Net.ServicePointManager.Expect100Continue = false;
         req.AllowWriteStreamBuffering = true;
         req.BeginGetRequestStream(GetRequestStreamCallback, req);
     }
     catch (Exception)
     {
         UpdateEnd(2);
     }
     return;
 }
        /// <summary>
        ///  Uploads the next chunk if there are more in queue.
        /// </summary>
        /// <returns>True/false if there are more chunks to be uploaded.</returns>
        public bool UploadNextChunk()
        {
            string url = this.uploadUrl;

            // Is there more chunks
            if (this.chunk >= this.chunks)
            {
                return(false);
            }

            this.syncContext = SynchronizationContext.Current;

            // Add name, chunk and chunks to query string when we don't use multipart
            if (!this.multipart)
            {
                if (url.IndexOf('?') == -1)
                {
                    url += '?';
                }

                url += "name=" + Uri.EscapeDataString(this.targetName);

                if (this.chunking)
                {
                    url += "&chunk=" + this.chunk;
                    url += "&chunks=" + this.chunks;
                }
            }

            HttpWebRequest req = WebRequest.Create(new Uri(HtmlPage.Document.DocumentUri, url)) as HttpWebRequest;

            req.Method = "POST";

            // Add custom headers
            if (this.headers != null)
            {
                foreach (string key in this.headers.Keys)
                {
                    req.Headers[key] = (string)this.headers[key];
                }
            }

            IAsyncResult asyncResult = req.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), req);

            return(true);
        }
Example #9
0
 public void SendRequest(Uri uri, byte[] postData, string contentType)
 {
     webRequest                   = (HttpWebRequest)WebRequest.Create(uri);
     webRequest.Method            = Method;
     webRequest.UserAgent         = UserAgents.RandomHumanAgent();
     webRequest.Accept            = "*/*";
     webRequest.AllowAutoRedirect = true;
     if (postData != null)
     {
         webRequest.ContentType = contentType;
         webRequest.BeginGetRequestStream(BeginRequest, postData);
     }
     else
     {
         webRequest.BeginGetResponse(BeginResponse, null);
     }
 }
Example #10
0
        public static void SocialPost(JObject obj, postResponseFunction finalCallbackFunction, string socialNetowrk, bool isPost)
        {
            HttpWebRequest req = HttpWebRequest.Create(new Uri(BASE + "/account/connect/" + socialNetowrk)) as HttpWebRequest;

            addToken(req);
            if (isPost)
            {
                req.Method      = "POST";
                req.ContentType = "application/json";
                req.BeginGetRequestStream(setParams_Callback, new object[] { req, RequestType.SOCIAL_POST, obj, finalCallbackFunction });
            }
            else
            {
                req.Method = "DELETE";
                req.BeginGetResponse(json_Callback, new object[] { req, RequestType.SOCIAL_DELETE, finalCallbackFunction });
            }
        }
Example #11
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is a <see cref="SparqlResultSet">SparqlResultSet</see> i.e. SELECT and ASK Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="handler">Results Handler</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultSet(ISparqlResultsHandler handler, String query, QueryCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
            request.Accept      = this.RdfAcceptHeader;

            Tools.HttpDebugRequest(request);

            request.BeginGetRequestStream(result =>
            {
                Stream stream = request.EndGetRequestStream(result);
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("query=");
                    writer.Write(HttpUtility.UrlEncode(query));

                    foreach (String u in this.DefaultGraphs)
                    {
                        writer.Write("&default-graph-uri=");
                        writer.Write(HttpUtility.UrlEncode(u));
                    }
                    foreach (String u in this.NamedGraphs)
                    {
                        writer.Write("&named-graph-uri=");
                        writer.Write(HttpUtility.UrlEncode(u));
                    }

                    writer.Close();
                }

                request.BeginGetResponse(innerResult =>
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult))
                    {
                        Tools.HttpDebugResponse(response);
                        ISparqlResultsReader parser = MimeTypesHelper.GetSparqlParser(response.ContentType, false);
                        parser.Load(handler, new StreamReader(response.GetResponseStream()));

                        response.Close();
                        callback(null, handler, state);
                    }
                }, null);
            }, null);
        }
        // Token: 0x0600120B RID: 4619 RVA: 0x0006D974 File Offset: 0x0006BB74
        internal void BeginSend(OwaContext owaContext, HttpRequest originalRequest, string targetUrl, string proxyRequestBody, AsyncCallback callback, object extraData)
        {
            ExTraceGlobals.ProxyCallTracer.TraceDebug((long)this.GetHashCode(), "ProxyProtocolRequest.BeginSend");
            Uri uri = new UriBuilder(owaContext.SecondCasUri.Uri)
            {
                Path = targetUrl
            }.Uri;
            HttpWebRequest proxyRequestInstance = ProxyUtilities.GetProxyRequestInstance(originalRequest, owaContext, uri);

            proxyRequestInstance.ContentLength = (long)((proxyRequestBody != null) ? Encoding.UTF8.GetByteCount(proxyRequestBody) : 0);
            proxyRequestInstance.Method        = "POST";
            this.proxyRequest     = proxyRequestInstance;
            this.proxyRequestBody = proxyRequestBody;
            this.owaContext       = owaContext;
            this.asyncResult      = new OwaAsyncResult(callback, extraData);
            proxyRequestInstance.BeginGetRequestStream(new AsyncCallback(this.GetRequestStreamCallback), this);
        }
 // Write post data to request buffer
 private void WritePostData(byte[] postData, Action <Exception> cb)
 {
     request.BeginGetRequestStream((IAsyncResult callbackResult) => {
         try
         {
             Stream postStream = request.EndGetRequestStream(callbackResult);
             postStream.Write(postData, 0, postData.Length);
             postStream.Close();
         }
         catch (Exception error)
         {
             cb(error);
             return;
         }
         cb(null);
     }, null);
 }
Example #14
0
        private void Signuppp(Object sender, EventArgs e)
        {
            // Create a new HttpWebRequest object.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://app.swclients.ch/ghassen/test.php");

            request.ContentType = "application/x-www-form-urlencoded";

            // Set the Method property to 'POST' to post data to the URI.
            request.Method = "POST";

            // start the asynchronous operation
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

            // Keep the main thread from continuing while the asynchronous
            // operation completes. A real world application
            // could do something useful such as updating its user interface.
        }
        // -------------------------------------------------------------------------

        /// <summary>
        /// makes a warmup request to the server and returns a response object in the form of RESPONSE_
        /// </summary>
        public static void make_request(CollabrifyClient c, HttpRequest__Object obj)
        {
            CollabrifyRequest_PB req_pb = new CollabrifyRequest_PB();

            req_pb.request_type = CollabrifyRequestType_PB.GET_CURRENT_ORDER_ID_REQUEST;

            HttpWebRequest request = obj.BuildRequest(req_pb);

            try
            {
                request.BeginGetRequestStream(new AsyncCallback(obj.getReqStream), request);
            }
            catch (WebException e)
            {
                System.Diagnostics.Debug.WriteLine("  -- EXCEPTION THROWN \n" + e.Message);
            }
        }
        /// <summary>
        /// Fetches the request asynchronously and calls one of the appropriate handlers when completed (likely on a separate thread).
        /// </summary>
        /// <typeparam name="TResponse">The type to deserialize the response object to</typeparam>
        /// <param name="handleWebException">Called if a WebException is generated</param>
        /// <param name="handleGenericException">Called if an Exception is generated</param>
        /// <param name="completedWithError">Called when either error handler completes</param>
        /// <param name="handleResponse">Called to handle the successful response with the deserialized response object</param>
        public void FetchAsync <TResponse>(
            Action <WebException> handleWebException,
            Action <Exception> handleGenericException,
            Action <Exception> completedWithError,
            Action <TResponse> handleResponse)
        {
            if (handleResponse == null)
            {
                throw new ArgumentNullException("handleResponse");
            }

            var _handleWebException = handleWebException ?? _defaultHandleWebException;
            var _handleException    = handleGenericException ?? _defaultHandleException;
            var _completedWithError = completedWithError ?? _defaultDoNothing;

            try
            {
                _bodyBytes = serializeBody();
                _auth.Authenticate(_request, _bodyBytes);
                _auth = null;

                var _handleResponse = handleResponse;

                var ast = new AsyncExecutionState <TResponse>(_bodyBytes, _request, _handleWebException, _handleException, _completedWithError, _deserializeBody, _handleResponse);

                if (_bodyBytes != null)
                {
                    // Send the body:
                    _request.BeginGetRequestStream(_completeGetRequestStream <TResponse>, ast);
                }
                else
                {
                    _request.BeginGetResponse(_completeGetResponse <TResponse>, ast);
                }
            }
            catch (WebException wex)
            {
                _handleWebException(wex);
                _completedWithError(wex);
            }
            catch (Exception ex)
            {
                _handleException(ex);
                _completedWithError(ex);
            }
        }
Example #17
0
        public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments)
        {
            if (_netConnection.ObjectEncoding == ObjectEncoding.AMF0)
                throw new NotSupportedException("AMF0 not supported for Flex RPC");
            try
            {
                TypeHelper._Init();

                Uri uri = new Uri(_gatewayUrl);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.ContentType = ContentType.AMF;
                request.Method = "POST";
            #if !(SILVERLIGHT)
                request.CookieContainer = _netConnection.CookieContainer;
            #endif
                AMFMessage amfMessage = new AMFMessage((ushort)_netConnection.ObjectEncoding);

                RemotingMessage remotingMessage = new RemotingMessage();
                remotingMessage.clientId = Guid.NewGuid().ToString("D");
                remotingMessage.destination = destination;
                remotingMessage.messageId = Guid.NewGuid().ToString("D");
                remotingMessage.timestamp = 0;
                remotingMessage.timeToLive = 0;
                remotingMessage.SetHeader(MessageBase.EndpointHeader, endpoint);
                remotingMessage.SetHeader(MessageBase.FlexClientIdHeader, _netConnection.ClientId ?? "nil");
                //Service stuff
                remotingMessage.source = source;
                remotingMessage.operation = operation;
                remotingMessage.body = arguments;

                foreach (KeyValuePair<string, AMFHeader> entry in _netConnection.Headers)
                {
                    amfMessage.AddHeader(entry.Value);
                }
                AMFBody amfBody = new AMFBody(null, null, new object[] { remotingMessage });
                amfMessage.AddBody(amfBody);

                PendingCall call = new PendingCall(source, operation, arguments);
                AmfRequestData amfRequestData = new AmfRequestData(request, amfMessage, call, callback, null);
                request.BeginGetRequestStream(BeginRequestFlexCall, amfRequestData);
            }
            catch (Exception ex)
            {
                _netConnection.RaiseNetStatus(ex);
            }
        }
Example #18
0
        private void ImgUploadFunc()
        {
            //String szRequestUrl = "http://127.0.0.1:8080/upload";
            String szRequestUrl = "http://WebBGTest-env-1.pef5ybuuuv.ap-northeast-1.elasticbeanstalk.com/upload";

            HttpWebRequest hRequest = (HttpWebRequest)WebRequest.Create(szRequestUrl);

            hRequest.Method      = "POST";
            hRequest.ContentType = "application/json";
            hRequest.Timeout     = 1000;

            try
            {
                hRequest.BeginGetRequestStream(RequestSteamResponse, hRequest);
            }
            catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); }
        }
        private void InvokeConfiguredRequest(AsyncResult asyncResult)
        {
            if (logger.IsDebugEnabled)
            {
                logger.DebugFormat("Starting request {0} at {1}", asyncResult.RequestName, this.config.ServiceURL);
            }

            if (asyncResult.RetriesAttempt > 0 && asyncResult.RequestStream != null)
            {
                asyncResult.RequestStream.Position = 0;
            }

            HttpWebRequest webRequest = ConfigureWebRequest(asyncResult);

            asyncResult.RequestState      = new AsyncResult.AsyncRequestState(webRequest, asyncResult.RequestData, asyncResult.RequestStream);
            asyncResult.RequestStartTicks = asyncResult.ElapsedTicks;

            if (asyncResult.CompletedSynchronously)
            {
                this.getRequestStreamCallback(asyncResult);
            }
            else
            {
                IAsyncResult httpResult;
                if (asyncResult != null &&
                    asyncResult.RequestState != null &&
                    (asyncResult.RequestState.WebRequest.Method == "POST" || asyncResult.RequestState.WebRequest.Method == "PUT"))
                {
                    httpResult = webRequest.BeginGetRequestStream(new AsyncCallback(this.getRequestStreamCallback), asyncResult);
                }
                else
                {
                    httpResult = webRequest.BeginGetResponse(new AsyncCallback(this.getResponseCallback), asyncResult);
                }

                if (httpResult.CompletedSynchronously)
                {
                    if (!asyncResult.RequestState.GetRequestStreamCallbackCalled)
                    {
                        getRequestStreamCallback(httpResult);
                    }
                    asyncResult.SetCompletedSynchronously(true);
                }
            }
        }
            //public void Create()
            //{
            //    var log = LogManager.GetLogger(Global.CallerName());

            //    try
            //    {
            //        log.Info(string.Format("xhr open {0}: {1}", Method, Uri));
            //        httpClient = new HttpClient();
            //        httpClient.DefaultRequestHeaders.Add("user-agent",
            //            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            //        httpClient.DefaultRequestHeaders.Add("Cookie",CookieHeaderValue);

            //        httpClient.MaxResponseContentBufferSize = 256000;


            //        HttpResponseMessage response = null;
            //        if (Method == "POST")
            //        {

            //            if (Data == null)
            //            {
            //                return;
            //            }
            //            HttpContent content = new ByteArrayContent(Data);
            //            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            //            var task = httpClient.PostAsync(Uri, content);
            //            task.Wait();
            //            if (task.IsFaulted)
            //            {
            //                throw new Exception(task.Exception.Message);
            //            }
            //            response = task.Result;
            //        }
            //        else if (Method == "GET")
            //        {
            //            var task = httpClient.GetAsync(Uri);
            //            task.Wait();
            //            if (task.IsFaulted)
            //            {
            //                throw new Exception(task.Exception.Message);
            //            }
            //            response = task.Result;
            //        }
            //        if (response == null)
            //        {
            //            log.Info("Response == null");
            //            return;
            //        }
            //        response.EnsureSuccessStatusCode();
            //        log.Info("Xhr.GetResponse ");

            //        var t = response.Headers;

            //        var responseHeaders = new Dictionary<string, string>();
            //        foreach (var h in response.Headers)
            //        {
            //            string value = "";
            //            foreach (var c in h.Value)
            //            {
            //                value += c;
            //            }

            //            responseHeaders.Add(h.Key, value);
            //        }
            //        OnResponseHeaders(responseHeaders);

            //        var contentType = responseHeaders.ContainsKey("Content-Type")
            //            ? responseHeaders["Content-Type"]
            //            : null;

            //        if (contentType != null &&
            //            contentType.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase))
            //        {
            //            var task = response.Content.ReadAsByteArrayAsync();
            //            task.ConfigureAwait(false);
            //            task.Wait();
            //            var responseBodyAsByteArray = task.Result;
            //            Task.Run(() => OnData(responseBodyAsByteArray)).Wait();
            //            //OnData(responseBodyAsByteArray);
            //        }
            //        else
            //        {
            //            var task = response.Content.ReadAsStringAsync();
            //            task.ConfigureAwait(false);
            //            task.Wait();
            //            var responseBodyAsText = task.Result;
            //            Task.Run(() => OnData(responseBodyAsText)).Wait();
            //            //OnData(responseBodyAsText);
            //        }

            //    }
            //    catch (Exception e)
            //    {
            //        log.Error(e);
            //        OnError(e);
            //        return;
            //    }
            //}



            public void Create()
            {
                var log = LogManager.GetLogger(Global.CallerName());

                try
                {
                    log.Info(string.Format("xhr open {0}: {1}", Method, Uri));

                    //http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx
                    httpWebRequest = (HttpWebRequest)WebRequest.Create(Uri);
                    //httpWebRequest.Headers["user-agent"] = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
                    // cannot do user agent??? see: http://stackoverflow.com/q/26249265/1109316


                    if (!string.IsNullOrEmpty(CookieHeaderValue))
                    {
                        httpWebRequest.Headers["Cookie"] = CookieHeaderValue;
                    }

                    httpWebRequest.Method = Method;

                    allDone = new ManualResetEvent(false);

                    if (Method == "POST")
                    {
                        if (Data == null)
                        {
                            return;
                        }
                        httpWebRequest.ContentType = "application/octet-stream";

                        httpWebRequest.BeginGetRequestStream(GetRequestStreamCallback, this);
                    }
                    else if (Method == "GET")
                    {
                        httpWebRequest.BeginGetResponse(GetResponseCallback, this);
                    }
                    allDone.WaitOne();
                }
                catch (Exception e)
                {
                    log.Error(e);
                    OnError(e);
                }
            }
Example #21
0
        static public void UploadFilesToServer(Uri uri, Dictionary <string, string> data, string fileName, string fileContentType, byte[] fileData)
        {
            string         boundary       = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            WebResponse    response       = null;

            httpWebRequest.ContentType     = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method          = "POST";
            httpWebRequest.CookieContainer = App.CookieManager.GetAllCookies();
            httpWebRequest.BeginGetRequestStream((result) =>
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                    using (Stream requestStream = request.EndGetRequestStream(result))
                    {
                        WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
                    }
                    request.BeginGetResponse(a =>
                    {
                        try
                        {
                            response           = request.EndGetResponse(a);
                            var responseStream = response.GetResponseStream();
                            using (var sr = new StreamReader(responseStream))
                            {
                                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                                {
                                    string responseString = streamReader.ReadToEnd();
                                    Debug.WriteLine("Reponse: " + responseString);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                    }, null);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                }
            }, httpWebRequest);
        }
Example #22
0
        /// <summary>
        /// 向服务端POST请求数据
        /// </summary>
        public static void POST(object data, Action <bool, WebExceptionStatus, ReturnResult> resultFunc, Uri url)
        {
            if (!inited)
            {
                throw new Exception("WebTools未初始化");
            }
            HttpWebRequest webRequest = WebRequest.CreateHttp(url);

            webRequest.Method = "POST";
            SetBasicAuthorization(webRequest);
            webRequest.ContentType = MediaType.APPLICATION_JSON;

            webRequest.BeginGetRequestStream(x =>
            {
                StreamWriter sw = new StreamWriter(webRequest.EndGetRequestStream(x), Encoding.UTF8);
                sw.Write(JsonConvert.SerializeObject(data)); //写入数据
                sw.Flush();
                sw.Dispose();
                webRequest.BeginGetResponse(y =>
                {
                    WebResponse response      = null;
                    bool suc                  = false;
                    WebExceptionStatus status = WebExceptionStatus.Success;
                    ReturnResult result       = null;
                    try
                    {
                        response = webRequest.EndGetResponse(y);
                        suc      = true;
                    }
                    catch (WebException ex)
                    {
                        status = ex.Status;
                    }

                    result = GetResultFromResponse(response);

                    if (resultFunc != null)
                    {
                        resultFunc(suc, status, result); //调用回调方法
                    }

                    result = null;
                }, null);
            }, null);
        }
Example #23
0
        /// <summary> InvokeMethodWeb
        /// Methoda pro pripojeni api ansynchronizacne
        /// <para>URI - is http url address. </para>
        /// <para>Parametrs - for method post. </para>
        /// </summary>
        public String InvokeMethodWeb(String uri, String parameters)
        {
            //getResponseData = "";

            try
            {
                // parameters: name1=value1&name2=value2
                HttpWebRequest webRequest_new = (HttpWebRequest)WebRequest.Create(uri);

                // Set the Method property of the request to POST.
                webRequest_new.Method = "POST";

                // Set the ContentType property of the WebRequest.
                webRequest_new.ContentType = "application/x-www-form-urlencoded";
                //webRequest.ContentType = "application/json";

                // Set parameters

                getParameters = parameters;

                // start the asynchronous operation
                webRequest_new.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest_new);

                // Keep the main thread from continuing while the asynchronous
                // operation completes. A real world application
                // could do something useful such as updating its user interface.
                //allDone.WaitOne(1500);
            }
            catch (WebException e)
            {
                Debug.WriteLine("\nException raised!");
                //MessageBox.Show(e.Message);
                Debug.WriteLine("\nStatus:{0}", e.Status);
                return(e.Message);
            }
            catch (Exception e)
            {
                Debug.WriteLine("\nException raised!");
                Debug.WriteLine("Source :{0} ", e.Source);
                //MessageBox.Show(e.Message);
                return(e.Message);
            }

            return(null);
        } // end HttpPost_API
        protected override void OnAcquireLicense(System.IO.Stream licenseChallenge, Uri licenseServerUri)
        {
            System.Diagnostics.Debug.WriteLine("+++++++++++++++++++++++++");
            ErrorMessage = "";
            StreamReader sr = new StreamReader(licenseChallenge);

            challengeString = sr.ReadToEnd();

            Uri resolvedLicenseServerUri;

            if (LicenseServerUriOverride == null)
            {
                string testuri = licenseServerUri.ToString().Replace("&amp;", "&");
                testuri = testuri + "&SessionId=D7D45D8D7090ACD4&Ticket=AFE578D8E05E22DE";

                Uri myUri = new Uri(testuri, UriKind.Absolute);
                resolvedLicenseServerUri = myUri;
            }
            else if (!LicenseServerUriOverride.IsAbsoluteUri)
            {
                string testuri = licenseServerUri.ToString().Replace("&amp;", "&");
                testuri = testuri + LicenseServerUriOverride.ToString();

                Uri myUri = new Uri(testuri, UriKind.Absolute);
                resolvedLicenseServerUri = myUri;
            }
            else
            {
                resolvedLicenseServerUri = LicenseServerUriOverride;
            }
            bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

            HttpWebRequest request = WebRequest.Create(resolvedLicenseServerUri) as HttpWebRequest;

            //HttpWebRequest request = (HttpWebRequest)System.Net.Browser.WebRequestCreator.ClientHttp.Create(resolvedLicenseServerUri);

            request.Method = "POST";

            request.ContentType = "application/xml";

            request.Headers["msprdrm_server_redirect_compat"]  = "false";
            request.Headers["msprdrm_server_exception_compat"] = "false";

            IAsyncResult asyncResult = request.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), request);
        }
Example #25
0
        private void RequestAsynch(Object parameters)
        {
            RequestParameters requestParameters = (RequestParameters)parameters;

            RequestState state = new RequestState()
            {
                PostBytes = requestParameters.PostBytes,
                Uri       = requestParameters.Uri,
                Verb      = requestParameters.Verb,
            };

            DateTime dtMetric = DateTime.UtcNow;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(state.Uri);

            request.Method      = requestParameters.Verb; // Post, Put, Delete
            request.ContentType = requestParameters.ContentType;

#if !SILVERLIGHT && !MONO
            request.ContentLength          = requestParameters.PostBytes.Length;
            request.AutomaticDecompression = DecompressionMethods.Deflate;
            request.KeepAlive = false;
#endif

            // To-Do: Refactor this central storage of header values to inject into an abstract network object.
            // inject request headers from iApp object.
            if (requestParameters.Headers != null && requestParameters.Headers.Count() > 0)
            {
                foreach (string key in requestParameters.Headers.Keys)
                {
                    request.Headers[key] = requestParameters.Headers[key];
                }
            }

            state.Request = request;

            // Start the asynchronous request.
            IAsyncResult result = request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), state);

            if (!allDone.WaitOne(DefaultTimeout))
            {
                OnError(state);
                return;
            }
        }
Example #26
0
        private void SendWebRequestAsync <TResponse>(string httpMethod, object request,
                                                     RequestState <TResponse> requestState, HttpWebRequest webRequest)
        {
            var httpGetOrDelete = (httpMethod == "GET" || httpMethod == "DELETE");

            webRequest.Accept = string.Format("{0}, */*", ContentType);

#if !SILVERLIGHT
            webRequest.Method = httpMethod;
#else
            //Methods others than GET and POST are only supported by Client request creator, see
            //http://msdn.microsoft.com/en-us/library/cc838250(v=vs.95).aspx

            if (this.UseBrowserHttpHandling && httpMethod != "GET" && httpMethod != "POST")
            {
                webRequest.Method = "POST";
                webRequest.Headers[HttpHeaders.XHttpMethodOverride] = httpMethod;
            }
            else
            {
                webRequest.Method = httpMethod;
            }
#endif

            if (this.Credentials != null)
            {
                webRequest.Credentials = this.Credentials;
            }


            if (HttpWebRequestFilter != null)
            {
                HttpWebRequestFilter(webRequest);
            }

            if (!httpGetOrDelete && request != null)
            {
                webRequest.ContentType = ContentType;
                webRequest.BeginGetRequestStream(RequestCallback <TResponse>, requestState);
            }
            else
            {
                requestState.WebRequest.BeginGetResponse(ResponseCallback <TResponse>, requestState);
            }
        }
Example #27
0
        /* Uploads data in the body of HTTP request */
        public string UploadData(Uri uri, Stream inputStream, string contentType)
        {
            Debug.WriteLine("Uri: " + uri.ToString());
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method      = HttpMethod.POST.ToString();
            request.ContentType = contentType;
            request.AllowWriteStreamBuffering = false;
            request.ContentLength             = inputStream.Length;

            IAsyncResult asyncRequest = request.BeginGetRequestStream(null, null);

            asyncRequest.AsyncWaitHandle.WaitOne(BASIC_TIMEOUT); // Wait untill stream is opened
            if (asyncRequest.IsCompleted)
            {
                try
                {
                    Stream webStream = request.EndGetRequestStream(asyncRequest);
                    inputStream.CopyTo(webStream);
                    inputStream.Dispose();
                    webStream.Flush();
                    webStream.Dispose();
                }
                catch (WebException err)
                {
                    throw new WebException("Unknown error: could not upload data.", err);
                }
            }
            else
            {
                throw new WebException("Timeout error: could not open stream for data uploading.");
            }

            IAsyncResult asyncResponse = request.BeginGetResponse(null, null);

            asyncResponse.AsyncWaitHandle.WaitOne();
            if (asyncResponse.IsCompleted)
            {
                return(ReadResponse(request, asyncResponse));
            }
            else
            {
                throw new TimeoutException("The HTTP session has timed out.");
            }
        }
Example #28
0
        /// <summary>
        /// Helper method for doing async update operations, callers just need to provide an appropriately prepared HTTP request and a RDF writer which will be used to write the data to the request body
        /// </summary>
        /// <param name="request">HTTP Request</param>
        /// <param name="writer">RDF writer</param>
        /// <param name="graphUri">URI of the Graph to update</param>
        /// <param name="ts">Triples</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        protected internal void UpdateGraphAsync(HttpWebRequest request, IRdfWriter writer, Uri graphUri, IEnumerable <Triple> ts, AsyncStorageCallback callback, Object state)
        {
            Graph g = new Graph();

            g.Assert(ts);

            request.BeginGetRequestStream(r =>
            {
                try
                {
                    Stream reqStream = request.EndGetRequestStream(r);
                    writer.Save(g, new StreamWriter(reqStream));

                    Tools.HttpDebugRequest(request);

                    request.BeginGetResponse(r2 =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                            Tools.HttpDebugResponse(response);
                            //If we get here then it was OK
                            response.Close();
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri), state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                }
            }, state);
        }
Example #29
0
        public void UploadFileEx()
        {
            Status = FileUploadStatus.Uploading;
            long temp = FileLength - BytesUploaded;

            UriBuilder ub       = new UriBuilder(UploadUrl);
            bool       complete = temp <= ChunkSize;

            ub.Query = string.Format("{4}filename={0}&StartByte={1}&Complete={2}&Random={3}",
                                     File.Name, BytesUploaded, complete,
                                     new Random().Next(),
                                     string.IsNullOrEmpty(ub.Query) ? "" : ub.Query.Remove(0, 1) + "&");

            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(ub.Uri);

            webrequest.Method = "POST";
            webrequest.BeginGetRequestStream(new AsyncCallback(WriteCallback), webrequest);
        }
Example #30
0
        public void logout()
        {
            email = thisApp.UserEmail;
            var uri = new Uri("http://dsjafhbvaio.appspot.com/action?Action=3&Email=" + email);

            //errorMessage.Text = "Connecting to server";

            Parameters = "?Email=" + email + "&Action = 3";

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);

            webRequest.Method = "POST";
            //webRequest.ContentType = "application/x-www-form-urlencoded";

            // Start web request
            webRequest.BeginGetRequestStream(new AsyncCallback(loginCallback), webRequest);
            (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative));
        }
Example #31
0
        public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer)
        {
            _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);

            IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetResponse(null, null);
            Assert.Throws<InvalidOperationException>(() =>
            {
                _savedHttpWebRequest.BeginGetRequestStream(null, null);
            });
        }
Example #32
0
        public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer)
        {
            _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer);
            _savedHttpWebRequest.Method = "POST";

            IAsyncResult asyncResult = _savedHttpWebRequest.BeginGetRequestStream(null, null);
            Assert.Throws<InvalidOperationException>(() =>
            {
                _savedHttpWebRequest.BeginGetRequestStream(null, null);
            });
        }
Example #33
0
File: test.cs Project: mono/gert
	static IAsyncResult BeginGetRequestStreamWithTimeout (HttpWebRequest request, AsyncCallback callback, object state, out RegisteredWaitHandle handle)
	{
		IAsyncResult asyncResult = request.BeginGetRequestStream (callback, state);

		handle = ThreadPool.RegisterWaitForSingleObject (
			asyncResult.AsyncWaitHandle,
			CancelRequest,
			request,
			1000,
			true);

		return asyncResult;
	}