I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Related
I obtain an access_token OK from Facebook, but whenever I try to use it, it fails (bad request).
It looks like the access_token is not being sent to the server correctly. I have used Server.UrlEncode to encode it.
Any ideas what I am doing wrong?
string ourAccessToken = "unknown";
//--------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
getAccessToken();
getMe();
}
// -----------------------
private void getAccessToken()
{
string result = "unknown";
try
{
// get app access token
string thisURL = "https://graph.facebook.com/oauth/access_token";
thisURL += "?client_id=" + ourClientID;
thisURL += "&client_secret=" + ourClientSecret;
thisURL += "&grant_type=client_credentials";
thisURL += "&redirect_uri=" + Server.UrlEncode(ourSiteRedirectURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception exc)
{
result = "ERROR : " + exc.ToString();
}
Response.Write( "<br>result=[" + result + "]");
// extract accessToken
string accessToken = "";
int equalsAt = result.IndexOf( "=");
if( equalsAt >= 0 && result.Length > equalsAt) accessToken = (result.Substring( equalsAt + 1)).Trim();
Response.Write( "<br>accessToken=[" + accessToken + "]");
ourAccessToken = accessToken;
}
// -----------------------
private void getMe()
{
string result = "unknown";
try
{
string thisURL = "https://graph.facebook.com/me?access_token=" + Server.UrlEncode(ourAccessToken);
Response.Write("<br>thisURL=" + thisURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception ex)
{
Response.Write("<br>getMe Exc: " + ex.Message.ToString() + "<br>");
}
Response.Write("<br>getMe result = " + result + "<br><br>");
}
Thanks
Right settings in App-Dashboard? If you active "Native/Desktop" you can not send API-Calls with this method, see:
https://developers.facebook.com/docs/facebook-login/access-tokens?locale=en_US#apptokens
After a lot of trial and error, I conclude that an App Access Token is not relevant, and that the ClientID and ClientSecret should be used directly. I want my App to generate a set of photographs of registered users. Because the server is making the call, there is no meaning to "me". A set of data can be obtained by preparing a batch process:
string p1 = "access_token=" + Server.UrlEncode(ourClientID + "|" + ourClientSecret);
string p2 = "&batch=" +
Server.UrlEncode( " [ { \"method\": \"get\", \"relative_url\": \"" + chrisFBID + "?fields=name,picture.type(square)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + johnFBID + "?fields=name,picture.type(large)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + stephFBID + "?fields=name,picture.type(large)\" } ]");
string responseData = "";
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
responseData = reader.ReadToEnd();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString() + "<br>");
}
Response.Write("<br>" + responseData + "<br><br>");
I also conclude that the FB documentation suffers from the usual fatal flaw of documentation: it has been written by an expert and never tested on a novice user before release.
I working in project that connect to appannie.com API and get result and it is working fine in debug but when I publish it and try to test it I get this page :
and here is the code used for this page in C#:
protected void Button1_Click(object sender, EventArgs e)
{
string url = "https://api.appannie.com/v1/accounts?page_index=0";
string id="",temp="";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UseDefaultCredentials = true;
request.Proxy = WebProxy.GetDefaultProxy();
request.Credentials = new NetworkCredential("username", "password");
request.ContentType = "Accept: application/xml";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Referer = "http://stackoverflow.com";
request.Headers.Add("Authorization", "bearer **************");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
temp = readStream.ReadToEnd();
//TextArea1.InnerText = temp + "\n";
string[] id_arr = temp.Split(',');
int count = 0;
while (count != id_arr.Length)
{
if (id_arr[count].Contains("account_id"))
{
id = id_arr[count];
count = id_arr.Length;
break;
}
count++;
}
id = id.Substring(id.IndexOf("account_id") + 13);
//TextArea1.InnerText += id;
//Console.Write(readStream.ReadToEnd());
//response.Close();
response = null;
//readStream.Close();
request = null;
string date = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
string url2 = "https://api.appannie.com/v1/accounts/" + id + "/sales?break_down=application+date" +
"&start_date="+date+
"&end_date="+date+
"¤cy=USD" +
"&countries=" +
"&page_index=0";
TextArea1.InnerText = url2;
request = (HttpWebRequest)WebRequest.Create(url2);
request.Proxy = WebProxy.GetDefaultProxy();
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Referer = "http://stackoverflow.com";
request.Headers.Add("Authorization", "bearer **************");
response = (HttpWebResponse)request.GetResponse();
receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
readStream = new StreamReader(receiveStream, Encoding.UTF8);
temp = "";
temp = readStream.ReadToEnd();
//TextArea1.InnerText = temp;
string[] id_arr2 = temp.Split(',');
int count2 = 0;
string down = "";
string update = "";
while (count2 != id_arr2.Length)
{
if (id_arr2[count2].Contains("downloads"))
{
down = id_arr2[count2];
count2 = id_arr2.Length;
break;
}
count2++;
}
count2 = 0;
while (count2 != id_arr2.Length)
{
if (id_arr2[count2].Contains("update"))
{
update = id_arr2[count2];
count2 = id_arr2.Length;
break;
}
count2++;
}
down = down.Substring(down.IndexOf("downloads") + 12);
update = update.Substring(update.IndexOf("update") + 9);
//TextArea1.InnerText = "downloads : "+down+ "----- update :" + update;
TextBox1.Text = down;
TextBox2.Text = update;
}
}
Once you publish it, one of the following is not taking effect:
Credentials
Proxy Settings.
Hence the remote api is giving back a 403. 2 ways to torubleshoot this further:
Run fiddler trace on the working request/response and compare it with the non-working request/response. Typically a good API has more details in the response body as to why it is a 403 error.. (token invalid, invalid credentials etc.)
You can also catch a WebException in code, and try to get the exception body if any. The same will also be visible in Fiddler.
<< code formatting refuses to work on my browser. please bear with unformatted code below >>
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// breakpoint and see what this is.
string errorDetails = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
i m testing authorize.net payments and it is working fine on local host payment processing is all good. but when i upload it to my live site with test accounts i get error with
**Object reference not set to an instance of an object. at Billing.readHtmlPage(String url)**
string[] authorizeServer = readHtmlPage("https://test.authorize.net/gateway/transact.dll").Split('|');
//Error is Here
if (authorizeServer[0].ToLower() == "approved" || authorizeServer[0].ToLower() == "1")
{
//Process Payment
}
private String readHtmlPage(string url)
{
String result = "";
//Test Account ID
String strPost =
"x_login=xxxxx"&x_type=AUTH_CAPTURE&x_method=CC&x_tran_key=xxxxx&x_relay_response=&FALSE&" + "x_card_num=" + ccNum.Text + "&x_exp_date=" + ddl_CCM.SelectedValue + "/" +
ddl_CCY.SelectedValue +
"&x_amount=" + lbl_Gtotal.Text +
"&x_first_name=" + ccFName.Text + "&x_last_name=" + ccLName.Text +
"&x_address=" + Server.UrlEncode(hf_street.Value) + "&x_city=" +
hf_city.Value +
"&x_state=" + hf_state.Value + "&x_zip=" + hf_zip.Value;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
Any Help would be nice and much helpful thanks
I'm trying to submit an HTML form through C# using the code below in the following WebPage:
http://liga.record.xl.pt/User/Login.aspx
I can't enter the page. Is that because it uses javascript to login?
private String readHtmlPage(string url)
{
String email = "email";
String password = "password";
String result = "";
String strPost = "email=" + email + "&password=" + password;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
the problem is the httpwebrequest method in my c# program. visual studio gives it a metric of 60, thats pretty lame.. so how can i program it more efficient? (:
my actual code:
public string httpRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Proxy = WebRequest.DefaultWebProxy;
request.MediaType = "HTTP/1.1";
request.ContentType = "text/xml";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
String sresp = streamr.ReadToEnd();
return sresp;
}
thanks for helping. ;)
Well, firstly I wouldnt let a number rule my code :)
However, using WebClient may simplify things quite a bit - less code to be counted. I'm not at a PC but that looks like a single DownloadString call, plus a few request headers.
http://msdn.microsoft.com/en-us/library/fhd1f0sw(v=VS.100).aspx
Oh, and add some using statements around all the IDisposable objects you create.
Here's the code I use in a social networking class I built which interacts with Twitter, Facebook, Tumblr, etc. Modify as you see fit. Also, I don't know what "metric" it would be given by VS, but if you're referring to the "Calculate Code Metrics" a 60 is still good. 20 to 100 is considered to be well maintainable, so I wouldn't worry too much.
protected string Request(
string Method,
Uri Endpoint,
string[][] Headers,
string Params) {
try {
ServicePointManager.Expect100Continue = false;
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Endpoint);
Request.Method = Method;
if (Method == "POST") {
Request.ContentLength = Params.Length;
Request.ContentType = "application/x-www-form-urlencoded";
};
for (byte a = 0, b = (byte)Headers.Length; a < b; a++) {
Request.Headers.Add(Headers[a][0], Headers[a][1]);
};
if (!String.IsNullOrWhiteSpace(Params)) {
using (StreamWriter Writer = new StreamWriter(Request.GetRequestStream())) {
Writer.Write(Params);
};
};
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
Request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointDelegate);
using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
} catch (WebException Ex) {
try {
if (Ex.Status != WebExceptionStatus.Success) {
using (StreamReader Reader = new StreamReader(Ex.Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
};
} catch (Exception) {
// Ignore
};
return (string.Empty);
} catch (Exception) {
return (string.Empty);
};
}
private IPEndPoint BindIPEndPointDelegate(
ServicePoint ServicePoint,
IPEndPoint RemoteEndPoint,
int Retries) {
if (String.IsNullOrWhiteSpace(this.IPEndpoint)) {
return new IPEndPoint(IPAddress.Any, 5000);
} else {
return new IPEndPoint(IPAddress.Parse(this.IPEndpoint), 5000);
};
}