FileUploadResponse MakeRequest(string url, string tag, MultipartBuilder requestBodyBuilder, IDictionary <string, string> headers = null) { //RequestBody requestBody = requestBodyBuilder.Build(); CountingRequestBody requestBody = new CountingRequestBody(requestBodyBuilder.Build(), tag, this); var requestBuilder = new Request.Builder(); if (headers != null) { foreach (string key in headers.Keys) { if (!string.IsNullOrEmpty(headers[key])) { requestBuilder = requestBuilder.AddHeader(key, headers[key]); } } } Request request = requestBuilder .Url(url) .Post(requestBody) .Build(); OkHttpClient client = new OkHttpClient(); client.SetConnectTimeout(ConnectUploadTimeout, UploadTimeoutUnit); // connect timeout client.SetReadTimeout(SocketUploadTimeout, UploadTimeoutUnit); // socket timeout Response response = client.NewCall(request).Execute(); var responseString = response.Body().String(); var code = response.Code(); IDictionary <string, string> responseHeaders = new Dictionary <string, string>(); var rHeaders = response.Headers(); if (rHeaders != null) { var names = rHeaders.Names(); foreach (string name in names) { if (!string.IsNullOrEmpty(rHeaders.Get(name))) { responseHeaders.Add(name, rHeaders.Get(name)); } } } FileUploadResponse fileUploadResponse = new FileUploadResponse(responseString, code, tag, new ReadOnlyDictionary <string, string>(responseHeaders)); if (response.IsSuccessful) { FileUploadCompleted(this, fileUploadResponse); } else { FileUploadError(this, fileUploadResponse); } return(fileUploadResponse); }
public async Task <string> GetRequest(string url) { string result = null; var client = new OkHttpClient(); try { var request = new Request.Builder() .Url(url) .Build(); var response = await client.NewCall(request).ExecuteAsync(); var body = response.Body().String(); result = body; } catch (Exception ex) { _logService.LogException(ex); } return(result); }
//Android3.0 以后已经不允许在主线程访问网络,报错android.os.NetworkOnMainThreadException //获取网页内容 public async System.Threading.Tasks.Task <string> Get(string url) { //连接超时5秒 //写入数据超时5秒 //读取数据超时5秒 client = new OkHttpClient.Builder() .ConnectTimeout(5, TimeUnit.Seconds) .WriteTimeout(5, TimeUnit.Seconds) .ReadTimeout(5, TimeUnit.Seconds) .Build(); Request request = new Request.Builder().Url(url).Build(); Response response = await client.NewCall(request).ExecuteAsync(); if (response.Code() == 200) { //Toast.MakeText(this, "response.Code() == 200", ToastLength.Short).Show(); var content = response.Body().String(); return(content); } else { return("null"); } }
private void getWeather(double latitude, double longitude) { string apiKey = "32b0b275eea19d641b0069e91c91b50a"; string apiUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude; if (isNetworkAvailable()) { RunOnUiThread(() => toggleRefresh()); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().Url(apiUrl).Build(); Call call = client.NewCall(request); call.Enqueue(response => { RunOnUiThread(() => toggleRefresh()); var jsonData = JObject.Parse(response.Body().String()); mCurrentWeather = getCurrentDetails(jsonData); RunOnUiThread(() => updateDisplay()); }, (req, exception) => { ShowError(); }); } else { Toast.MakeText(this, "Network unavailable", ToastLength.Long).Show(); } }
string LoadAWOkHttpClientAsync(string urlText) { Response response = null; try { OkHttpClient clientOrg = new OkHttpClient(); OkHttpClient client = AWOkHttpClient.CopyWithDefaults(clientOrg, new AllowAllTrustManager()); Request request = new Request.Builder() .Url(urlText) .Build(); response = client.NewCall(request).Execute(); string responseCode = "Response Code: " + response.Code(); return(responseCode); } catch (IOException e) { return("IO Exception during network request"); } finally { if (response != null) { response.Body().Close(); } } }
public static void sendOkHttpRequests(string address, Okhttp3.ICallback callbck) { var client = new OkHttpClient(); Okhttp3.Request requests = new Request.Builder().Url(address).Build(); requests.Url(); client.NewCall(requests).Enqueue(callbck); }
public void Run() { Request request = new Request.Builder() .Url(IdHostAdress + AccessPoint.Bssid) .AddHeader("Authorization", "Bearer " + _token) .Build(); client.NewCall(request).Enqueue(this); }
public async System.Threading.Tasks.Task <bool> Post(string url, Object user) { FormBody.Builder formBody = new FormBody.Builder(); //创建表单请求体 formBody.Add("name", "1"); formBody.Add("pwd", "2"); Request request = new Request.Builder().AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").Url(url).Post(formBody.Build()).Build(); var response = await httpClient.NewCall(request).ExecuteAsync(); if (response.Code() == 200) { var result = JsonConvert.DeserializeObject <string>(response.Body().String()); if (result == "success") { return(true); } return(false); } return(false); }
private void CallToken() { dialog.Show(); Request request = new Request.Builder() .Url("http://technobee.elementstore.ru/api/person/") .AddHeader("Authorization", "Bearer " + settings.Token) .Build(); client.NewCall(request).Enqueue(this); }
public void doTheThing(Action <List <Character> > characters) { try{ MD5 md5 = System.Security.Cryptography.MD5.Create(); DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var timeStamp = (long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds); string api_key = "insert public key hear"; string private_key = "insert private key here"; byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(timeStamp + private_key + api_key); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } var thing = sb.ToString().ToLower(); ; var url = new URL("https://gateway.marvel.com:443/v1/public/characters?apikey=550bdabffb29d3cc2bf6813a68021ee4&hash=" + thing + "&ts=" + timeStamp + "&limit=10");//+ "&format=json"); //var uriBuilder = new UriBuilder(); //uriBuilder.Scheme = "https"; //uriBuilder.Host = "gateway.marvel.com"; //uriBuilder.Path = "v1/public/characters"; //uriBuilder.Query = "apikey=550bdabffb29d3cc2bf6813a68021ee4"; //uriBuilder. OkHttpClient client = new OkHttpClient(); Request request = new Request .Builder() .Url(url) .Build(); Response response = client.NewCall(request).Execute(); var body = response.Body().String().Replace('\"', '"'); var x = Newtonsoft.Json.JsonConvert.DeserializeObject <RootObject>(body); var things = x.data.results; characters(things); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public async Task <Tuple <Boolean, String> > ResolveClusterUrlAsync(String clusterUrl) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .Url(clusterUrl) .Build(); Response response = await client.NewCall(request).ExecuteAsync(); String server = await response.Body().StringAsync(); return(new Tuple <bool, String>(response.IsSuccessful, server)); }
private async void MakeHttpCall() { #if __ANDROID__ var client = new OkHttpClient(); var requestBody = RequestBody.Create( MediaType.Parse("application/json"), "{\"title\":\"foo\",\"body\": \"bar\", \"userId\":\"1\", \"id\":\"1\"}"); var request = new Request.Builder() .Url("https://jsonplaceholder.typicode.com/posts") .Post(requestBody) .Build(); var response = await client.NewCall(request).ExecuteAsync(); #endif }
public override void OnCreate() { base.OnCreate(); userId = JwtHelper.GetAspNetUserId(UserSettings.Token); dbWriter = new SignalsDBWriter(this); timer = new Timer { Interval = 30000, Enabled = true }; timer.Elapsed += (s, e) => { Logger.Info("trying to sent telemetry..."); var type = MediaType.Parse("application/json; charset=utf-8"); var telemetry = dbWriter.ReadTelemetry(userId, out ids); if (telemetry?.Count > 0) { var str = Newtonsoft.Json.JsonConvert.SerializeObject(telemetry, new Trigger.Classes.TelemetryJsonConverter()); var body = RequestBody.Create(type, str); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .Url(Url) .Header("scn-dev-msg", "") .Post(body) .Build(); Callback c = new Callback { Writer = dbWriter, Ids = ids }; var all_signals = telemetry.SelectMany(b => b.Select(i => i)).ToList(); Logger.Info("Send Telemetry: " + all_signals.Count.ToString()); client.NewCall(request).Enqueue(c); } else { Logger.Info("No signals to send"); } }; }
private async Task <HttpResponseMessage> HttpGet(string url) { var client = new OkHttpClient(); client.SetHostnameVerifier(new HostnameVerifier()); client.SetSslSocketFactory(GetSocketFactory()); var builder = new Request.Builder() .Method("GET", null) .Url(url) .CacheControl(new CacheControl.Builder().NoCache().Build()) .AddHeader("User-Agent", "Test/1.0"); var rq = builder.Build(); var call = client.NewCall(rq); System.Diagnostics.Debug.WriteLine("Sending Call..."); var resp = await call.EnqueueAsync().ConfigureAwait(false); System.Diagnostics.Debug.WriteLine("Got response"); var respBody = resp.Body(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); ret.ReasonPhrase = resp.Message(); if (respBody != null) { ret.Content = new StreamContent(respBody.ByteStream()); } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); Button download = FindViewById <Button>(Resource.Id.download); ListView listView = FindViewById <ListView>(Resource.Id.listView); download.Click += async delegate { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.SetLevel(HttpLoggingInterceptor.Level.Basic); OkHttpClient client = new OkHttpClient().NewBuilder() .AddInterceptor(logging) .Build(); // Create request for remote resource. Request request = new Request.Builder() .Url(Endpoint) .Build(); // Execute the request and retrieve the response. Response response = await client.NewCall(request).ExecuteAsync(); // Deserialize HTTP response to concrete type. string body = await response.Body().StringAsync(); List <Contributor> contributors = JsonConvert.DeserializeObject <List <Contributor> >(body); // Sort list by the most contributions. List <string> data = contributors .OrderByDescending(c => c.contributions) .Select(c => string.Format("{0} ({1})", c.login, c.contributions)) .ToList(); // Output list of contributors. IListAdapter adapter = new ArrayAdapter <string>( this, Android.Resource.Layout.SimpleListItem1, Android.Resource.Id.Text1, data); listView.Adapter = adapter; }; }
private void GetComments() //在主线程更新UI { OkHttpClient client = new OkHttpClient(); var Endpoint = string.Format(@"http://cacakaka.com:8000/api/Video/GetVideoCommons?vid={0}&pageIndex={1}&pageSize={2}", 1, 1, 20);// "http://47.91.249.226:8000/api/Video/GetAllVideos"; // Create request for remote resource. Request request = new Request.Builder() .Url(Endpoint) .Build(); // Execute the request and retrieve the response. Response response = client.NewCall(request).ExecuteAsync().Result; // Deserialize HTTP response to concrete type. string body = response.Body().StringAsync().Result; comments = new List <ArticleComment>(); comments = JsonConvert.DeserializeObject <List <ArticleComment> >(body); }
FileUploadResponse MakeRequest(string url, string tag, MultipartBuilder requestBodyBuilder, IDictionary <string, string> headers = null) { //RequestBody requestBody = requestBodyBuilder.Build(); CountingRequestBody requestBody = new CountingRequestBody(requestBodyBuilder.Build(), this); var requestBuilder = new Request.Builder(); if (headers != null) { foreach (string key in headers.Keys) { if (!string.IsNullOrEmpty(headers[key])) { requestBuilder = requestBuilder.AddHeader(key, headers[key]); } } } Request request = requestBuilder .Url(url) .Post(requestBody) .Build(); OkHttpClient client = new OkHttpClient(); client.SetConnectTimeout(5, TimeUnit.Minutes); // connect timeout client.SetReadTimeout(5, TimeUnit.Minutes); // socket timeout Response response = client.NewCall(request).Execute(); var responseString = response.Body().String(); var code = response.Code(); var fileUploadResponse = new FileUploadResponse(responseString, code, tag); if (response.IsSuccessful) { FileUploadCompleted(this, fileUploadResponse); return(fileUploadResponse); } else { FileUploadError(this, fileUploadResponse); return(fileUploadResponse); } }
private void LoadUrl(String url) { Request request; try { request = new Request.Builder() .Url(url) .Build(); } catch (Exception ex) { OnLoadError(); return; } if (this.client == null) { this.client = new OkHttpClient(); } client.NewCall(request).Enqueue((ICall call, Response response) => { if (!response.IsSuccessful) { OnLoadError(); } try { JSONObject json = new JSONObject(response.Body().String()); LottieComposition.Factory.FromJson(this.Resources, json, (composition) => { SetComposition(composition, "Network Animation"); }); } catch (JSONException ex) { OnLoadError(); } }, (ICall call, Java.IO.IOException e) => OnLoadError()); }
private void Login() { settings.Login = etLogin.Text; settings.Password = etPassword.Text; var json = Newtonsoft.Json.JsonConvert.SerializeObject(new LoginData { Login = etLogin.Text, Password = etPassword.Text }); var type = MediaType.Parse("application / json; charset = utf - 8"); RequestBody body = RequestBody.Create(type, json); Request request = new Request.Builder() .Url(UrlLogin) .Header("Content-Type", "application/json") .Post(body) .Build(); client.NewCall(request).Enqueue(this); }
private void GetValue(Message msg)//在主线程更新UI { var msgStr = msg.What; OkHttpClient client = new OkHttpClient(); var Endpoint = "http://47.91.249.226:8000/api/Video/GetAllVideos"; // Create request for remote resource. Request request = new Request.Builder() .Url(Endpoint) .Build(); // Execute the request and retrieve the response. Response response = client.NewCall(request).ExecuteAsync().Result; // Deserialize HTTP response to concrete type. string body = response.Body().StringAsync().Result; list = new List <VideoModel>(); list = JsonConvert.DeserializeObject <List <VideoModel> >(body); }
//下载图片 public async System.Threading.Tasks.Task <byte[]> GetPicture(string url) { client = new OkHttpClient.Builder() .ConnectTimeout(5, TimeUnit.Seconds) .WriteTimeout(5, TimeUnit.Seconds) .ReadTimeout(5, TimeUnit.Seconds) .Build(); Request request = new Request.Builder().Url(url).Build(); Response response = await client.NewCall(request).ExecuteAsync(); if (response.Code() == 200) { var bytes = await response.Body().BytesAsync(); return(bytes); } else { return(null); } }
public async void CustomNetworkEvent() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .Url(CUSTOMURL) .Post(RequestBody.Create(Square.OkHttp3.MediaType.Parse("text/x-markdown; charset=utf-8"), REQUESTBODY)) .Build(); // Define custom network event NetworkMeasure networkMeasure = APMS.Instance.CreateNetworkMeasure(CUSTOMURL, "POST"); networkMeasure.SetBytesSent(request.Headers().ByteCount()); long bytesReceive = 0L; networkMeasure.Start(); try { Response response = await okHttpClient.NewCall(request).ExecuteAsync(); networkMeasure.SetStatusCode(response.Code()); if (response.Body() != null) { networkMeasure.SetBytesReceived(response.Body().ContentLength()); networkMeasure.SetContentType(response.Body().ContentType().ToString()); bytesReceive = DealResponseBody(response.Body()); response.Body().Close(); } networkMeasure.PutProperty("Property", bytesReceive.ToString()); networkMeasure.Stop(); } catch (Exception ex) { networkMeasure.SetStatusCode(0); networkMeasure.PutProperty("Error Message", ex.Message); networkMeasure.PutProperty("Bytes", bytesReceive.ToString()); networkMeasure.Stop(); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Button download = FindViewById<Button>(Resource.Id.download); ListView listView = FindViewById<ListView>(Resource.Id.listView); download.Click += async delegate { OkHttpClient client = new OkHttpClient(); // Create request for remote resource. Request request = new Request.Builder() .Url(Endpoint) .Build(); // Execute the request and retrieve the response. Response response = await client.NewCall(request).ExecuteAsync(); // Deserialize HTTP response to concrete type. string body = await response.Body().StringAsync(); List<Contributor> contributors = JsonConvert.DeserializeObject<List<Contributor>>(body); // Sort list by the most contributions. List<string> data = contributors .OrderByDescending(c => c.contributions) .Select(c => string.Format("{0} ({1})", c.login, c.contributions)) .ToList(); // Output list of contributors. IListAdapter adapter = new ArrayAdapter<string>( this, Android.Resource.Layout.SimpleListItem1, Android.Resource.Id.Text1, data); listView.Adapter = adapter; }; }
public async Task <string> GetResponseString(string url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .Url("https://www.google.com") .Build(); try { // Synchronous blocking call Response response = await client.NewCall(request).ExecuteAsync(); string body = response.Body().String(); return(body); } catch (Exception ex) { int i = 1; return(null); } }
public void Run() { var data = new UserData { Version = "0.1", Id = "1", // id пользователя DeviceId = _deviceId, TimeStart = DateTime.Now }; string json = JsonConvert.SerializeObject(data); RequestBody body = RequestBody.Create(MediaType.Parse("application/json; charset=utf-8"), json); Request request = new Request.Builder() .Url(_ipAddress) .AddHeader("Phone-Action", "hello") .AddHeader("Content-Type", "application/json; charset=utf-8") .Post(body) .Build(); client.NewCall(request).Enqueue(this); }
public async Task <AppUpdateModel> GetServicesVersion() { var searchurl = GlobalSetting.Instance.GatewayLogisticEndpoint + "/api/App/get?id=Android_TmsLogisticerApp"; OkHttpClient client = new OkHttpClient(); OkHttpClient mOkHttpClient = client.NewBuilder() .SslSocketFactory(HttpsTrustManager.createSSLSocketFactory(), new HttpsTrustManager()) .HostnameVerifier(new TrustAllHostnameVerifier()) .Build(); Request request = new Request.Builder().Url(searchurl).Get().Build(); ICall call = mOkHttpClient.NewCall(request); var response = await call.ExecuteAsync(); var content = await response.Body().StringAsync(); var appupdatemodel = JsonConvert.DeserializeObject <AppUpdateModel>(content); return(appupdatemodel); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(java_uri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes); } var builder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); var keyValuePairs = request.Headers .Union(request.Content != null ? (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers : Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()); foreach (var kvp in keyValuePairs) { builder.AddHeader(kvp.Key, String.Join(",", kvp.Value)); } cancellationToken.ThrowIfCancellationRequested(); var rq = builder.Build(); var call = client.NewCall(rq); cancellationToken.Register(() => call.Cancel()); var resp = default(Response); try { resp = await call.EnqueueAsync().ConfigureAwait(false); } catch (IOException ex) { if (ex.Message.ToLowerInvariant().Contains("canceled")) { throw new OperationCanceledException(); } throw; } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); if (respBody != null) { var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken); content.Progress = getAndRemoveCallbackFromRegister(request); ret.Content = content; } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(java_uri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var contentType = "text/plain"; if (request.Content.Headers.ContentType != null) { contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type")); } body = RequestBody.Create(MediaType.Parse(contentType), bytes); } var requestBuilder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); if (DisableCaching) { requestBuilder.CacheControl(noCacheCacheControl); } var keyValuePairs = request.Headers .Union(request.Content != null ? request.Content.Headers : Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()); // Add Cookie Header if there's any cookie for the domain in the cookie jar var stringBuilder = new StringBuilder(); if (client.CookieJar() != null) { var jar = client.CookieJar(); var cookies = jar.LoadForRequest(HttpUrl.Get(url)); foreach (var cookie in cookies) { stringBuilder.Append(cookie.Name() + "=" + cookie.Value() + ";"); } } foreach (var kvp in keyValuePairs) { if (kvp.Key == "Cookie") { foreach (var val in kvp.Value) { stringBuilder.Append(val + ";"); } } else { requestBuilder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value)); } } if (stringBuilder.Length > 0) { requestBuilder.AddHeader("Cookie", stringBuilder.ToString().TrimEnd(';')); } if (Timeout != null) { var clientBuilder = client.NewBuilder(); var timeout = (long)Timeout.Value.TotalSeconds; clientBuilder.ConnectTimeout(timeout, TimeUnit.Seconds); clientBuilder.WriteTimeout(timeout, TimeUnit.Seconds); clientBuilder.ReadTimeout(timeout, TimeUnit.Seconds); client = clientBuilder.Build(); } cancellationToken.ThrowIfCancellationRequested(); var rq = requestBuilder.Build(); var call = client.NewCall(rq); // NB: Even closing a socket must be done off the UI thread. Cray! cancellationToken.Register(() => Task.Run(() => call.Cancel())); var resp = default(Response); try { resp = await call.EnqueueAsync().ConfigureAwait(false); var newReq = resp.Request(); var newUri = newReq == null ? null : newReq.Url().Uri(); request.RequestUri = new Uri(newUri.ToString()); if (throwOnCaptiveNetwork && newUri != null) { if (url.Host != newUri.Host) { throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString())); } } } catch (IOException ex) { if (ex.Message.ToLowerInvariant().Contains("canceled")) { throw new System.OperationCanceledException(); } // Calling HttpClient methods should throw .Net Exception when fail #5 throw new HttpRequestException(ex.Message, ex); } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); ret.RequestMessage = request; ret.ReasonPhrase = resp.Message(); // ReasonPhrase is empty under HTTPS #8 if (string.IsNullOrEmpty(ret.ReasonPhrase)) { try { ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' '); } #pragma warning disable 0168 catch (Exception ex) { ret.ReasonPhrase = "Unassigned"; } #pragma warning restore 0168 } if (respBody != null) { var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None); content.Progress = getAndRemoveCallbackFromRegister(request); ret.Content = content; } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(java_uri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var contentType = "text/plain"; if (request.Content.Headers.ContentType != null) { contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type")); } body = RequestBody.Create(bytes, MediaType.Parse(contentType)); } var requestBuilder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); requestBuilder.CacheControl(_noCacheCacheControl); foreach (var kvp in request.Headers) { requestBuilder.AddHeader(kvp.Key, String.Join(",", kvp.Value)); } cancellationToken.ThrowIfCancellationRequested(); var rq = requestBuilder.Build(); var call = _client.NewCall(rq); // NB: Even closing a socket must be done off the UI thread. Cray! cancellationToken.Register(() => Task.Run(() => call.Cancel())); var resp = default(Response); try { resp = await call.EnqueueAsync().ConfigureAwait(false); // 重定向 //var newReq = resp.Request(); //var newUri = newReq == null ? null : newReq.Url().Uri(); //request.RequestUri = new Uri(newUri.ToString()); //if (throwOnCaptiveNetwork && newUri != null) //{ // if (url.Host != newUri.Host) // { // throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString())); // } //} } catch (IOException ex) { if (ex.Message.ToLowerInvariant().Contains("canceled")) { throw new System.OperationCanceledException(); } // Calling HttpClient methods should throw .Net Exception when fail #5 throw new HttpRequestException(ex.Message, ex); } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); ret.RequestMessage = request; ret.ReasonPhrase = resp.Message(); // ReasonPhrase is empty under HTTPS #8 if (string.IsNullOrEmpty(ret.ReasonPhrase)) { try { ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' '); } #pragma warning disable 0168 catch (Exception ex) { ret.ReasonPhrase = "Unassigned"; } #pragma warning restore 0168 } if (respBody != null) { var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None); content.Progress = GetAndRemoveCallbackFromRegister(request); ret.Content = content; } else { ret.Content = new ByteArrayContent(new byte[0]); } // 响应头 var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (_client == null) { _client = _builder.Build(); } var javaUri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(javaUri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var contentType = "text/plain"; if (request.Content.Headers.ContentType != null) { contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type")); } body = RequestBody.Create(MediaType.Parse(contentType), bytes); } var builder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); var keyValuePairs = request.Headers .Union(request.Content != null ? request.Content.Headers : Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()); foreach (var kvp in keyValuePairs) { var headerSeparator = kvp.Key == "User-Agent" ? " " : ","; builder.AddHeader(kvp.Key, string.Join(headerSeparator, kvp.Value)); } cancellationToken.ThrowIfCancellationRequested(); var rq = builder.Build(); var call = _client.NewCall(rq); // NB: Even closing a socket must be done off the UI thread. Cray! cancellationToken.Register(() => Task.Run(() => call.Cancel())); Response resp; try { resp = await call.ExecuteAsync().ConfigureAwait(false); } catch (IOException ex) { if (ex.Message != null && ex.Message.StartsWith("Certificate pinning failure!")) { throw new WebException(ex.Message, WebExceptionStatus.TrustFailure); } if (ex.Message != null && ex.Message.ToLowerInvariant().Contains("canceled")) { throw new System.OperationCanceledException(); } throw; } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()) { RequestMessage = request, ReasonPhrase = resp.Message() }; if (respBody != null) { ret.Content = new StreamContent(respBody.ByteStream()); } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped); var url = new Java.Net.URL(java_uri); var body = default(RequestBody); if (request.Content != null) { var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var contentType = "text/plain"; if (request.Content.Headers.ContentType != null) { contentType = String.Join(" ", request.Content.Headers.GetValues("Content-Type")); } body = RequestBody.Create(MediaType.Parse(contentType), bytes); } var builder = new Request.Builder() .Method(request.Method.Method.ToUpperInvariant(), body) .Url(url); if (DisableCaching) { builder.CacheControl(noCacheCacheControl); } var keyValuePairs = request.Headers .Union(request.Content != null ? (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers : Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()); foreach (var kvp in keyValuePairs) { builder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value)); } cancellationToken.ThrowIfCancellationRequested(); var rq = builder.Build(); var call = client.NewCall(rq); // NB: Even closing a socket must be done off the UI thread. Cray! cancellationToken.Register(() => Task.Run(() => call.Cancel())); var resp = default(Response); try { resp = await call.EnqueueAsync().ConfigureAwait(false); var newReq = resp.Request(); var newUri = newReq == null ? null : newReq.Uri(); request.RequestUri = new Uri(newUri.ToString()); if (throwOnCaptiveNetwork && newUri != null) { if (url.Host != newUri.Host) { throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString())); } } } catch (IOException ex) { if (ex.Message.ToLowerInvariant().Contains("canceled")) { throw new OperationCanceledException(); } throw; } var respBody = resp.Body(); cancellationToken.ThrowIfCancellationRequested(); var ret = new HttpResponseMessage((HttpStatusCode)resp.Code()); ret.RequestMessage = request; ret.ReasonPhrase = resp.Message(); if (respBody != null) { var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None); content.Progress = getAndRemoveCallbackFromRegister(request); ret.Content = content; } else { ret.Content = new ByteArrayContent(new byte[0]); } var respHeaders = resp.Headers(); foreach (var k in respHeaders.Names()) { ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k)); } return(ret); }
private void getWeather(double latitude, double longitude) { string apiKey = "32b0b275eea19d641b0069e91c91b50a"; string apiUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude; if (isNetworkAvailable ()) { RunOnUiThread(() => toggleRefresh()); OkHttpClient client = new OkHttpClient (); Request request = new Request.Builder ().Url (apiUrl).Build (); Call call = client.NewCall (request); call.Enqueue (response => { RunOnUiThread(() => toggleRefresh()); var jsonData = JObject.Parse (response.Body ().String ()); mCurrentWeather = getCurrentDetails (jsonData); RunOnUiThread(() => updateDisplay()); }, (req, exception) => { ShowError (); }); } else { Toast.MakeText (this, "Network unavailable", ToastLength.Long).Show (); } }