Linked In API (auth token (oauth2)) c#.net - c#

I wonder if someone can give me some pointers on using the linked in API. I thought I had it sussed but for some reason when trying to get the auth_token I just get http 400 Bad Request.
My code, simply is:
public string redirectUrl = URLTOREDIRECT;
public String apiKey = APIKEY;
public String apiSecret = APISECRET;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=apiKey&scope=rw_company_admin&state=DCEEFWF45453sdffef424&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl));
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + _consumerkey + "&client_secret=" + _consumerSecret;
// var postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code, HttpUtility.HtmlEncode(redirectUrl), apiKey, apiSecret);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
//This "application/x-www-form-urlencoded"; line is important
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = sign.Length;
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(sign);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
return responseReader.ReadToEnd().ToString() ;
}
The code is all in the same page for testing purposes and is the same page as the redirectUrl.
Really stumped, tried all variations.
First bit clearly works as I get directed to linked in to allow app. The second part getting the auth token fails.

After much head scratching, eureka moment - did not need to send the info in the request.
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
//byte[] byteArray = Encoding.UTF8.GetBytes(sign);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
return returnVal;

I'm Using this code and it's working fine..... C# code ASP.NET :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LI
{
public partial class WebForm3 : System.Web.UI.Page
{
public string redirectUrl = "http://localhost:64576/WebForm3";
public string TokenGlobe = "";
public String apiKey = "API_KEY";
public string retval = "";
public String apiSecret = "API_Secret";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void btnTwit_Click(object sender, EventArgs e)
{
var Address = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + apiKey + "&redirect_uri=http://localhost:64576/WebForm3&state=987654321&scope=w_share";
using (var webClient = new WebClient())
{
webClient.Headers.Add("x-li-format", "json");
}
Response.Redirect(Address);
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/oauth/v2/accessToken";
var sign1 = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" + apiKey + "&client_secret=" + apiSecret + "";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
HttpWebRequest webRequest = System.Net.WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Host = "www.linkedin.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
var stri = redirectUrl;
retval = returnVal.ToString();
var objects = JsonConvert.DeserializeObject<Accountdsdsd>(retval);//JArray.Parse(retval);
TokenGlobe = objects.access_token;
var SentStatus = PostLinkedInNetworkUpdate(TokenGlobe, "Hello API"); //Share
return TokenGlobe;
// return responseReader.ReadToEnd().ToString();
}
private string linkedinSharesEndPoint = "https://api.linkedin.com//v1/people/~/shares?oauth2_access_token={0}&format=json";
private const string defaultUrl = "http://localhost:64576/WebForm3";
private const string defaultImageUrl = "http://opusleads.com/opusing/technology/technology%20(1).jpg"; //Image To Post
public bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = defaultUrl, string submittedImageUrl = defaultImageUrl)
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
//Json Parsing
public class Accountdsdsd
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
}

Related

consuming a soap webservice-getting 500

I have a 500 error when trying to consume a soap WS .
code below :
main function :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
sendrequest method :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
public static string SendSOAPRequest(string url, string action,Dictionary<string, string> parameters, bool useSOAP12 = false)
{
try{
XmlDocument soapEnvelopeXml = new XmlDocument();
var xmlStr = (useSOAP12)
? #"XXXXXX";
string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
soapEnvelopeXml.LoadXml(s);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + action));
webRequest.Headers.Add("SOAPAction", url);
webRequest.Headers.Add("XXXXXX", "AG6YUTGV6");
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "GET";
string usernamePassword = "username" + ":" + "pass";
usernamePassword = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
CredentialCache mycache = new CredentialCache();
webRequest.Credentials = mycache;
webRequest.Headers.Add("Authorization", "Basic " + usernamePassword);
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
string result;
using (WebResponse response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
result = rd.ReadToEnd();
}
}
return result;
}
catch (WebException ex)
{
string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return "";
}

cockies is null when HttpWebResponse in formauthentication

I have an application where I used signalr. and formAuthentication. I am trying to connect hub class from WCF service. IN WCF service code is as bellow:
Public Class Demo
{
public Demo()
{
var connection = new HubConnection("http://localhost:47315/")
{
CookieContainer = new CookieContainer()
};
connection.CookieContainer.Add(GetAuthCookie("user1", "pass"));
chatHubProxy = connection.CreateHubProxy("servicesSatatuseHub");
connection.Start().Wait();
}
private static System.Net.Cookie GetAuthCookie(string user, string pass)
{
//var http = WebRequest.Create("http://localhost:47315/module/account/login.aspx") as HttpWebRequest;
var http = WebRequest.Create("http://localhost:47315//module/account/login.aspx") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
//var postData = "UserName=" + user + "&Password=" + pass + "";
var postData = "UserName=" + user + "&Password=" + pass + "";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
System.Net.Cookie authCookie;
using (var response = http.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
}
httpResponse.Close();
return cookie;
}
}
Every thing is fine but Cookie is null on this code
authCookie = <p>response.Cookies[FormsAuthentication.FormsCookieName];//authCookie = null
Due to cookie null hubconnection is fail.
Thanks in advance

Googleplus authentication: OAuth 2 parameters can only have a single value: code

I am trying to implement Googleplus login on my site using Oauth2.
I would like to pass state parameter which will be used once the user is successfully authenticated.
The error i am getting is "OAuth 2 parameters can only have a single value: code".
If i do not use the state parameter, it is working fine and authenticating the user.
Below is my code:
protected void Page_Load(object sender, EventArgs e)
{
string returnPath = Request.QueryString["ReturnUrl"];
if (returnPath == null)
{
returnPath = "ManageAccount.aspx";
}
else
{
returnPath = Request.QueryString["ReturnUrl"].ToString();
}
Session["state"] = returnPath;
if (Session["Provider"] != null)
{
if (Session["Provider"].ToString() == "Google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
getgoogleplususerdataSer(accessToken);
}
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
lblMessage.Text = error;
}
}
}
}
}
}
}
protected void btnGoogleLogin_Click(object sender, System.EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id + "&state=" + Session["state"];
Session["Provider"] = "Google";
Response.Redirect(Googleurl);
}
What could i be doing wrong?
I decided to avoid the state parameter. Instead i stored the ReturnUrl in a cookie for use after successful authentication.
returnPath = Request.QueryString["ReturnUrl"];
if (returnPath == null)
{
returnPath = "ManageAccount.aspx";
}
else
{
returnPath = Request.QueryString["ReturnUrl"].ToString();
}
//Create a cookie to redirect user after login
HttpCookie rCookie = new HttpCookie("RedirectCookie");
DateTime now = DateTime.Now;
rCookie.Value = returnPath;
Response.Cookies.Add(rCookie);

Automatic add text on textbox when I open one site

So, i'm tring to put one information on one textbox, in more special textbox, CNPJ of one site:
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp
but I'm not getting... so, what I have tried... I have tried to put the cnpj value on the final of link, like this:
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp?cnpj=00495835000160
but, the site no put the value on the text box...
How I can make to enter with with the cnpj value on the site ( whiout digit on the site, just in the link... )
And, In C# I have tried this:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ReceitaFederal
{
class Program
{
static void Main(string[] args)
{
try
{
WebRequest request = WebRequest.Create("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp");
string strPost = "cnpj=00495835000160";
request.Method = "POST";
request.ContentLength = strPost.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(strPost);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Console.WriteLine(responseFromServer);
}
catch (Exception exec)
{
Console.WriteLine(exec.GetType() + "" + exec.Message);
}
}
}
}
Solved!!! First add this cookie container:
using System;
using System.Net;
namespace ConsultaCNPJ
{
public class CookieAwareWebClient : WebClient
{
private CookieContainer _mContainer;
public void SetCookieContainer(CookieContainer container)
{
_mContainer = container;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
var webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = _mContainer;
webRequest.KeepAlive = true;
webRequest.ProtocolVersion = HttpVersion.Version10;
}
return request;
}
}
}
Then edit you code to this:
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsultaCNPJ
{
public class ConsultaCNPJBroker
{
private readonly CookieContainer _cookies = new CookieContainer();
public String DominioReceitaFederal = "http://www.receita.fazenda.gov.br";
public String GetDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
public String PostDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/valida.asp";
private String _viewState;
public Bitmap GetCaptcha()
{
const string strViewState = "<input type=hidden id=viewstate name=viewstate value='";
const string strImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
String htmlResult;
using (var wc = new CookieAwareWebClient())
{
wc.SetCookieContainer(_cookies);
wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
wc.Headers[HttpRequestHeader.KeepAlive] = "300";
htmlResult = wc.DownloadString(DominioReceitaFederal + GetDataReceitaFederal);
}
if (htmlResult.Length > 0)
{
_viewState = htmlResult;
int posString = _viewState.IndexOf(strViewState, StringComparison.Ordinal);
_viewState = _viewState.Substring(posString + strViewState.Length);
posString = _viewState.IndexOf("'>", StringComparison.Ordinal);
_viewState = _viewState.Substring(0, posString);
String urlImagemCaptcha = htmlResult;
posString = urlImagemCaptcha.IndexOf(strImagemCaptcha, StringComparison.Ordinal);
urlImagemCaptcha = urlImagemCaptcha.Substring(posString + strImagemCaptcha.Length);
posString = urlImagemCaptcha.IndexOf("'>", StringComparison.Ordinal);
urlImagemCaptcha = urlImagemCaptcha.Substring(0, posString);
urlImagemCaptcha = urlImagemCaptcha.Replace("amp;", "");
if (urlImagemCaptcha.Length > 0)
{
var wc2 = new CookieAwareWebClient();
wc2.SetCookieContainer(_cookies);
wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
wc2.Headers[HttpRequestHeader.KeepAlive] = "300";
byte[] data = wc2.DownloadData(DominioReceitaFederal + urlImagemCaptcha);
return new Bitmap(
new MemoryStream(data));
}
return null;
}
_viewState = "";
return null;
}
public Stream Consulta(string aCNPJ, string aCaptcha, bool removerEspacosDuplos)
{
var request = (HttpWebRequest) WebRequest.Create(DominioReceitaFederal + PostDataReceitaFederal);
request.ProtocolVersion = HttpVersion.Version10;
request.CookieContainer = _cookies;
request.Method = "POST";
string fviewstate = _viewState;
fviewstate = Uri.EscapeDataString((fviewstate));
string postData = "";
postData = postData + "origem=comprovante&";
postData = postData + "viewstate=" + fviewstate + "&";
postData = postData + "cnpj=" + new Regex(#"[^\d]").Replace(aCNPJ, string.Empty) + "&";
postData = postData + "captcha=" + aCaptcha + "&";
postData = postData + "captchaAudio=&";
postData = postData + "submit1=Consultar&";
postData = postData + "search_type=cnpj";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
return response.GetResponseStream();
}
}
}
That's it!
Special thanks to my great friend CunhaW!
Usage:
First create a form with a PictureBox and a TextBox and the broker for captcha like this
private readonly ConsultaCNPJBroker _broker = new ConsultaCNPJBroker();
this.ImgCaptcha = new System.Windows.Forms.PictureBox();
this.TbxCaptcha = new System.Windows.Forms.TextBox();
Then use like 2-Steps query, first get the Captcha then do the Query with the captcha
private void UpdateCaptcha()
{
ImgCaptcha.Image = _broker.GetCaptcha();
TbxCaptcha.Text = string.Empty;
}
A user interaction is need here to solve the captcha and fill the textbox and finally
private void BtnExecute_OnClick(object sender, EventArgs e)
{
var pessoaJuridica = _broker.Consulta(TbxCNPJ.Text, TbxCaptcha.Text, true);
// here you can see props like pessoaJuridica.CNPJ
}
Maybe this help you, it's not working yet... but almost there...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Windows.Forms;
namespace LeituraWeb
{
public partial class Form1 : Form
{
String viewState;
public String Dominio_ReceitaFederal = "http://www.receita.fazenda.gov.br/";
public String GetData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
public String PostData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/valida.asp";
public Form1()
{
InitializeComponent();
}
private void btnGo_Click(object sender, EventArgs e)
{
int PosString;
String StrViewState = "<input type=hidden id=viewstate name=viewstate value='";
String StrImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
String UrlImagemCaptcha = "";
String HtmlResult = "";
using (WebClient wc = new WebClient()){
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
HtmlResult = wc.DownloadString(Dominio_ReceitaFederal + GetData_ReceitaFederal);
}
if (HtmlResult.Length > 0)
{
viewState = HtmlResult;
// executando um crop do viewstate para utilizar no post
PosString = viewState.IndexOf(StrViewState);
viewState = viewState.Substring(PosString + StrViewState.Length);
PosString = viewState.IndexOf("'>");
viewState = viewState.Substring(0, PosString);
//executando um crop na url da imagem
UrlImagemCaptcha = HtmlResult;
PosString = UrlImagemCaptcha.IndexOf(StrImagemCaptcha);
UrlImagemCaptcha = UrlImagemCaptcha.Substring(PosString + StrImagemCaptcha.Length);
PosString = UrlImagemCaptcha.IndexOf("'>");
UrlImagemCaptcha = UrlImagemCaptcha.Substring(0, PosString);
UrlImagemCaptcha = UrlImagemCaptcha.Replace("amp;", "");
// populando a imagem do captcha dentro de um picturebox
if (UrlImagemCaptcha.Length > 0)
pictureBox1.Image = new System.Drawing.Bitmap(new System.IO.MemoryStream(new System.Net.WebClient().DownloadData(Dominio_ReceitaFederal + UrlImagemCaptcha)));
}
else
{
viewState = "";
}
}
private void button1_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create(Dominio_ReceitaFederal + PostData_ReceitaFederal);
// Formatando o ViewState Recebido
string fviewstate = viewState;
fviewstate = System.Uri.EscapeDataString(System.Uri.UnescapeDataString(fviewstate));
// inserindo os campos a serem postados
string postData = "";
postData = postData + "origem=comprovante&";
postData = postData + "viewstate=" + fviewstate + "&";
postData = postData + "cnpj=00000000000000&";
postData = postData + "captcha=000000&";
postData = postData + "captchaAudio=&";
postData = postData + "submit1=Consultar&";
postData = postData + "search_type=cnpj";
// montando a requisicao
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// ---------- erro aqui !!!
// retorno da sefaz ---- sempre retorna -- Parametros Inválidos
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
}
}
You have to make sure the target site supports the kind of request you are trying to do.
If not, you are out of luck. Keep in mind that the web app implementation is the one who dictates the rules, not you.
Additionally, it looks like you are trying to obtain information from a Brazilian government site. Usually, this type of sites have mechanisms to prevent what you are trying to achieve, such as captchas and domain validation.
The good news is that, also usually, government sites publish rules and manuals on how to access public webservices. However, you also usually need permission for that.
The page uses frames:
<frame name="top" scrolling="no" frameborder="0" marginheight="0" noresize="true" target="contents" src="cabecalho.htm" marginwidth="0" marginheight="0">
<frame frameborder="0" name="main" SRC="cnpjreva_solicitacao2.asp" scrolling="auto" noresize="false" marginheight="0" marginwidth="0">
The main frame contains the page cnpjreva_solicitacao2.asp, so calling http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp?cnpj=00495835000160 (see the 2 in the page file name) will show you the content of the main frame with the CNPJ filled as passed by the parameter.
I say instead of crafting the resulting code,
you could inject javascript.
e.g.
open the page you posted
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp
open JS Console and type the following:
document.getElementsByName("main")[0].contentDocument.getElementsByName("cnpj")[0].value = "MyNewValue"
Notice, the form is within a frame element, so you need to get the frame element and then the input element.
You can do the same via the Web Browser API.
Good Luck with solving the CAPTCHA

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Categories