C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

In 4.0 version of the .Net framework the ServicePointManager.SecurityProtocol only offered two options to set: Ssl3: Secure Socket Layer (SSL) 3.0 security protocol. Tls: Transport Layer Security (TLS) 1.0 security protocol In the next release of the framework the SecurityProtocolType enumerator got extended with the newer Tls protocols, so if your application can use th … Read more

Receiving JSON data back from HTTP request

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method. The HttpClient class documentation includes this example: HttpClient … Read more

How can I retrieve IP address from HTTP header in Java [duplicate]

Use the getHeader(String Name) method of the javax.servlet.http.HttpServletRequest object to retrieve the value of Remote_Addr variable. Here is the sample code: String ipAddress = request.getHeader(“Remote_Addr”); If this code returns empty string, then use this way: String ipAddress = request.getHeader(“HTTP_X_FORWARDED_FOR”); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); }

C# HttpWebRequest of type “application/x-www-form-urlencoded” – how to send ‘&’ character in content body?

First install “Microsoft ASP.NET Web API Client” nuget package: PM > Install-Package Microsoft.AspNet.WebApi.Client Then use the following function to post your data: public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData) { using (var httpClient = new HttpClient()) { using (var content = new FormUrlEncodedContent(postData)) { content.Headers.Clear(); content.Headers.Add(“Content-Type”, “application/x-www-form-urlencoded”); HttpResponseMessage response = await httpClient.PostAsync(url, content); … Read more

GetResponseAsync does not accept cancellationToken

Something like this should work (untested): public static class Extensions { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } } } In theory, if cancellation is requested on ct and request.Abort is invoked, await request.GetResponseAsync() should throw … Read more