The SSL connection could not be established. ASP.NET MVC - c#

While debugging this part of code, i am getting
The SSL connection could not be established
Can anybody provide a solution?
WebRequest wr = WebRequest.Create(URL);
wr.Method = "DELETE";
using (WebResponse objResponse = wr.GetResponse())
{
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
string Res = sr.ReadToEnd();
sr.Close();
}
objResponse.Close();
}

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = data.Length;
request.ServerCertificateValidationCallback = (sender, cert, chain, error) => { return true; };
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(data);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
return responseReader.ReadToEnd();
}
}
catch (Exception e)
{
return e.Message;
}

Related

308 permanent redirect with uploading PDF to REST API

I want to upload PDF to CrossEngage platform using HttpWebRequest or RestClient. As response I'm getting : 308 permanent redirect, but when i try this on POSTMAN all is fine (200 OK). What i'm not doing that POSTMAN is doing ?
//RestClient
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
string converted = Convert.ToBase64String(dataBytes);
var client = new RestClient(Url+Action);
client.FollowRedirects = true;
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("x-xng-authtoken", AuthToken);
request.AddHeader("x-xng-apiversion", "2");
request.AddHeader("content-type", "application/pdf");
request.AddParameter("application/pdf", converted, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response.Content;
//HttpWebRequest
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 1;
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;
request.ContentLength = 0;
request.CookieContainer = new CookieContainer();
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}
I expect 200 OK status code
Thanks in advance
UPDATE: I have found a solution so it might help someone.
Simply you need to call location given in Location response header.
Hereby complete code :
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = false;
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
{
var uriString = response.Headers["Location"];
var apiClient = (HttpWebRequest)WebRequest.Create(uriString);
apiClient.ContentType = contentType;
apiClient.Method = method;
apiClient.AllowAutoRedirect = false;
apiClient.Accept = "*/*";
apiClient.Headers.Add("X-XNG-ApiVersion", "2");
apiClient.Headers.Add("X-XNG-AuthToken", AuthToken);
apiClient.ContentLength = dataBytes.Length;
using (Stream requestBody = apiClient.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
var r = apiClient.GetResponse();
}
response.Close();
}
return "";
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}

Login into iCloud via Json Post request

I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}

How to post video properties with youtube-data-api on c#

I try to upload videos to my youtube account with youtube api v3 on asp.net. I searched a lot but didn't find any code sample to do this. Actually now i can upload videos somehow but i can't give name, description etc. to my videos. Here's my code which i use to upload my videos.
Uri uri = new Uri("https://www.googleapis.com/upload/youtube/v3/videos?part=snippet");
WebClient wc = new WebClient();
wc.Headers.Add("Authorization", "Bearer {access_token}");
byte[] file = File.ReadAllBytes(Server.MapPath("/videos/test.mp4"));
byte[] response = wc.UploadData(uri, file);
string jSonResult = String.Format("\nResult received was {0}",
Encoding.ASCII.GetString(response));
return jSonResult;
Don't know if you already found a solution.
But this code works on my machine! ;)
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
//byte[] file = File.ReadAllBytes(videoFilePath);
using (var fileStream = new FileStream(videoFilePath, FileMode.Open))
{
Uri uri = new Uri("https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + authToken);
request.ContentLength = jsonBytes.Length;
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("X-Upload-Content-Length", fileStream.Length.ToString());
request.Headers.Add("X-Upload-Content-Type", "video/*");
string location = string.Empty;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(jsonBytes, 0, jsonBytes.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
location = response.Headers["Location"];
}
}
catch (WebException ex)
{
Response.Write(ex.ToString());
}
request = (HttpWebRequest) WebRequest.Create(location);
request.Method = "PUT";
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + authToken);
request.ContentLength = fileStream.Length;
request.ContentType = "video/*";
using (Stream dataStream = request.GetRequestStream())
{
byte[] buffer = new byte[fileStream.Length];
var data = fileStream.Read(buffer, 0, buffer.Length);
dataStream.Write(buffer, 0, data);
//dataStream.Write(file, 0, file.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
}
}
catch (WebException ex)
{
Response.Write(ex.ToString());
}

What is the alternative to JQuery post in ASP.NET C#

What is the alternative to Jquery post in asp.net C#
var scrapyd_url = 'http://www.domain.com/';
var project_name = 'xxxx';
var spider_name = 'yyy';
$.post(scrapyd_url + 'schedule.json', {
project: project_name,
spider: spider_name
});
I think you will like webrequest and webresponse class amde for this purpose only # http://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx
An example (Copied)
public string SendPost(string url, string postData)
{
string webpageContent = string.Empty;
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw;
}
return webpageContent;
}

Facing issue with creating a push notification service for Android using Google C2DM Service with asp.net mvc3

Guyz facing problems with creating a push notification service (for android) using Google C2DM which uses OAuth 2.0 . I am sort of newbie dev , and the deadline is on the head ! Please help !
In the above question there was only one issue . I had lost my cool and was into tremendous pressure. This doesn't work well with intellectual property. So , with a bit of mental peace above simple issue was solved.
Guyz below given is the code for the dummies like me :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using System.Collections;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Configuration;
using System.Web.Script.Serialization;
using PushNotification.Entities;
namespace PushNotification
{
public class AndroidCommunicationService
{
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public string GetAuthenticationCode()
{
string returnUrl = "";
string URL = "https://accounts.google.com/o/oauth2/auth";
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("response_type", "code");
postFieldNameValue.Add("scope", "https://android.apis.google.com/c2dm/send");
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"].ToString());
postFieldNameValue.Add("redirect_uri", "http://localhost:8080/TestServer/test");
postFieldNameValue.Add("state", "profile");
postFieldNameValue.Add("access_type", "offline");
postFieldNameValue.Add("approval_prompt", "auto");
postFieldNameValue.Add("additional_param", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var sr = new StreamReader(Response.GetResponseStream());
// You can do this and return the content on the screen ( I am using MVC )
returnUrl = sr.ReadToEnd();
// Or
returnUrl = Response.RedirectUri.ToString();
}
catch
{
throw ;
}
return returnUrl;
}
public TokenResponse GetNewToken(string Code)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("code", Code);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("redirect_uri", ConfigurationManager.AppSettings["RedirectUrl"]);
postFieldNameValue.Add("grant_type", "authorization_code");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch (WebException wex)
{
var sr = new StreamReader(wex.Response.GetResponseStream());
Exception ex = new WebException(sr.ReadToEnd() + wex.Message);
throw ex;
}
return tokenResponse;
}
public TokenResponse RefreshToken(string RefreshToken)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("refresh_token", RefreshToken);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("grant_type", "refresh_token");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch
{
throw;
}
return tokenResponse;
}
public string SendPushMessage(string RegistrationId, string Message ,string AuthString)
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["PushMessageUrl"]);
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("registration_id", RegistrationId);
postFieldNameValue.Add("collapse_key", "fav_Message");
postFieldNameValue.Add("data.message", Message);
postFieldNameValue.Add("additional_value", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
// This is to be sent as a header and not as a param .
Request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AuthString);
try
{
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return responseLine;
}
catch
{
throw;
}
}
private string GetPostStringFrom(NameValueCollection postFieldNameValue)
{
//throw new NotImplementedException();
List<string> items = new List<string>();
foreach (String name in postFieldNameValue)
items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(postFieldNameValue[name])));
return String.Join("&", items.ToArray());
}
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
}
}
public class TokenResponse
{
public String access_token{ get; set; }
public String expires_in { get; set; }
public String token_type { get; set; }
public String refresh_token { get; set; }
}

Categories