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);
};
}
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 have list word i need to send all this word on webrequest POST method
like here :
this function to request>
private void RequesteUrl(string word)
{
// try
// {
CookieContainer WeBCookies = new CookieContainer();
HttpWebRequest url = (HttpWebRequest)WebRequest.Create("http://mbc.com/index.php");
url.Method = "POST";
url.UserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:44.0) Gecko/20100101 Firefox/44.0";
url.Referer = "http://mbc.com/index.php?";
var PostData = User.Text + "&password=" + word;
var Data = Encoding.ASCII.GetBytes(PostData);
url.ContentLength = Data.Length;
url.Host = "www.mbc.com";
url.ContentType = "application/x-www-form-urlencoded";
// url.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);
url.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
url.KeepAlive = true;
url.Headers.Add("Cookie: "+tryit);
using (var stream = url.GetRequestStream())
{
stream.Write(Data, 0, Data.Length);
}
HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse();
int status = (int)WebResponse.StatusCode;
Stream ST = WebResponse.GetResponseStream();
StreamReader STreader = new StreamReader(ST);
string RR = STreader.ReadToEnd();
// MessageBox.Show (status.ToString() + " " + word);
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message);
// }
}
and i use this to load :
foreach (string selectword in Lists)
{
RequesteUrl(selectword);
}
but foreach not complete all list , he do to two from list only !
Yes, the reason is that you are not releasing resources after your request is complete. Since HTTP/1.1 only allows two simultaneous connections per server, after two requests you will run out of available connections. That is why it hangs.
You need to close the HttpWebResponse, and also good idea to close the streamreader and stream....
using(HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse())
{
int status = (int)WebResponse.StatusCode;
using(Stream ST = WebResponse.GetResponseStream())
using(StreamReader STreader = new StreamReader(ST))
string RR = STreader.ReadToEnd();
}
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;
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
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.site.ru/group/" + gr);
request.AllowAutoRedirect = false;
request.Method = "GET";
request.CookieContainer = cookies;
request.UserAgent = "Opera/9.80 (Windows 7; U; en) Presto/2.9.168 Version/11.50";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response_headers = (HttpWebResponse)request.GetResponse();
System.IO.Stream stream = response_headers.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string response = sr.ReadToEnd();
sr.Close();
/*if (response_headers.Headers["Location"].Contains("alted"))
{
log("[-] GROUP is " + gr + " closed\r\n");
return -2;
}*/
string gash = Regex.Match(response, #"gwtHash:""(?<id>[^""]+)""").Groups["id"].Value;
string grpId = Regex.Match(response, #"state:""st.cmd=altGroupMain&st.groupId=(?<id>[^""]+)""").Groups["id"].Value;
}
catch { log("[?] Can't parse ash and grpId\r\n"); return -1; }
This code works successfully when constraction if {} is commented. But when I delete comment and run it I receive [?] Can't parse ash and grpId
Why?=\
response_headers.Headers["Location"] must be null, so it raise exception. Insert verification:
if (response_headers.Headers["Location"] != null && response_headers.Headers["Location"].Contains("alted"))
{
log("[-] GROUP is " + gr + " closed\r\n");
return -2;
}
You get that message because you have a catch everything block around all your code:
catch { log("[?] Can't parse ash and grpId\r\n"); return -1; }
This is a bad practice. Remove the try/catch block and let the original exception show itself. This will make it possible to see what the real problem is.