RestSharp - Request to Spotify API - spotify

RestClient Client = new RestClient(Settings.Url)
{
UserAgent = Settings.UserAgent,
FollowRedirects = false
};
RestRequest Req = new RestRequest(Method.POST);
Req.AddHeader("Content-Type", Settings.ContentType);
Req.AddHeader("Accept", "application/json, text/plain, */*");
Req.AddHeader("Accept-Encoding", "gzip, deflate, br");
Req.AddHeader("Accept-Language", "en-US,en;q=0.9");
Req.AddHeader("Referer", Settings.Referer);
Req.AddParameter("remember=false&username=xxx&password=xxx&captcha_token=&csrf_token=", ParameterType.RequestBody);
Client.ExecuteAsync(Req, response =>
{
if (response.StatusCode == HttpStatusCode.BadRequest)
{
Console.WriteLine("Access DENIED!", Color.DarkRed);
}
else
{
Console.WriteLine("Accessed.", Color.Green);
}
});
This is my basic Request.
here is my Class Settings:
public class Settings
{
public static string Url = "https://accounts.spotify.com/api/login";
public static string Referer = "https://accounts.spotify.com/en/login/";
public static string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36";
public static string ContentType = "application/x-www-form-urlencoded";
}
So my problem is that I always get the Access Denied even if I put in correct details.
This is how the Form Data looks like:
remember: true
username: fsdfsdfds
password: sfdfdsfsd
captcha_token:
csrf_token: AQC-Y5OnqJvcV1PLrsvXFU-FdVNANBKZOpB5S3vDxCKH0VpPE3flpkMNJKheqQGzut066RziyASQSDeB-Tj7I0TSKtmtZ3FKs6tLMnCUkES4Lr2aKwIy8mh80NWtX70uU-i6
Do I need to bypass the CSRF_Token somehow?
Or can you find another Error?

Related

Gecko WebBrowser unable to open a specific link first time after Restart machine

I am new in C# . I have developed own webbrowser with Gecko webBrowser control. But I'm unable to open a particular link for first time, and it return alert for timeout. I handled timeout alert messagebox too.
When I have implemented
private void gWebBrowser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
I found out that first time page was not properly loaded.
How can i use auto Reload or timer in it?
My code is:
public partial class Embedded_Browser : Form
{
public Embedded_Browser()
{
string GeminiURL = "NA";
InitializeComponent();
Xpcom.Initialize("Firefox");
GeckoPreferences.User["dom.max_script_run_time"] = 0; //let js run as long as it needs to; prevents timeout errors
GeckoPreferences.User["security.warn_viewing_mixed"] = false;
GeckoPreferences.User["browser.download.manager.showAlertOnComplete"] = false;
GeckoPreferences.User["privacy.popups.showBrowserMessage"] = false;
GeckoPreferences.User["browser.xul.error_pages.enabled"] = false;
GeckoPreferences.User["browser.cache.memory.enable"] = false;
gWebBrowser.NSSError += new EventHandler<GeckoNSSErrorEventArgs>(gWebBrowser_NSSError); //Bypass SSL certificate issues
gWebBrowser.NavigationError += new EventHandler<GeckoNavigationErrorEventArgs>(gWebBrowser_NavigationError); //If there are any issues encountered during page loads
gWebBrowser.Navigated += new EventHandler<GeckoNavigatedEventArgs>(gWebBrowser_Navigated); //React appropriately to URL navigation
string sUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)";
Gecko.GeckoPreferences.User["general.useragent.override"] = sUserAgent;
var observerService = Xpcom.GetService<nsIObserverService>("#mozilla.org/observer-service;1");
observerService.AddObserver(new Observer(), "http-on-modify-request", false);
if (Environment.Is64BitOperatingSystem)
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
else
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
gWebBrowser.Navigate(GeminiURL);
textBox1.Text = GeminiURL;
PromptFactory.PromptServiceCreator = () => new NoPromptService();
// System.Threading.Thread.Sleep(5000);
if(NoPromptService.isPrompt == 1){
gWebBrowser.Reload();
gWebBrowser.Navigate(GeminiURL);
MessageBox.Show("Hello!");
}
}
Please Help me. thanks in advance
I have used timer control for making Web browser auto refresh for first time.
After 5ms web browser auto refresh once.
My code is:
private void timer1_Tick(object sender, EventArgs e)
{
gWebBrowser.Navigate("google.com"); //You can pass any url here which you want to load
if (count == 0)
{
timer1.Enabled = false;
}
count++;
}

tomcat access log get my eth0 ip?

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%t %a %A %p %r %q %s %B %D %{User-Agent}i %{Referer}i"
resolveHosts="false" />
This is my server.xml ,then i found the result is like this:
[29/Mar/2017:10:36:16 +0800] 192.168.5.149 127.0.0.1 80 GET /favicon.ico HTTP/1.1 404 0 0 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0 -
in the server.xml %A just give me the loop ip, but i want eth0 ip ..
So what should i do? Thanks a lot!
Check host name:
$ hostname
yourhost
Edit /etc/hosts and add:
192.168.5.1 yourhost
FYI, Tomcat source code:
/**
* write local IP address - %A
*/
protected static class LocalAddrElement implements AccessLogElement {
private static final String LOCAL_ADDR_VALUE;
static {
String init;
try {
init = InetAddress.getLocalHost().getHostAddress();
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
init = "127.0.0.1";
}
LOCAL_ADDR_VALUE = init;
}
#Override
public void addElement(StringBuilder buf, Date date, Request request,
Response response, long time) {
buf.append(LOCAL_ADDR_VALUE);
}
}

Streaming a file download in managed bean action invoked by a dynamically created CommandButton has no effect

So I have a method that is correctly creating a CSV file with a bunch of data when called by doGet(HttpServletRequest request, HttpServletResponse response) which is called when I create a button like this:
link = new HtmlOutputLink();
HtmlGraphicImage img = new HtmlGraphicImage();
img.setStyle("background-color: #FFFFFF;");
img.setTitle("Click to Export these requests to csv file");
img.setValue("../images/Export.PNG");
link.getChildren().add(img);
link.setValue(resp.encodeURL(Constants.TXT_ALL_DIV_TEAM_EXPORT_LINK));
cell = new DataTableCell();
cell.setType(CellType.DATA);
cell.setFormat(new Format(Format.CENTER));
cell.addElement(link);
headerRow.addElement(cell);
When the button is clicked the doGet method then calls the method which creates the CSV file (which, again, is working correctly called from doGet).
However, I have to change this from an image to a CommandButton, the command button is a custom class that extends the javax.faces.component.html.HtmlCommandButton package, so now I have this:
HtmlOutputLink link = new HtmlOutputLink();
CommandButton alertsButton = new CommandButton();
alertsButton.setId(UI_EXPORT_ID);
alertsButton.setValue(UI_EXPORT_TXT);
alertsButton.setOnclick("javascript:showWaitLayer();jsCBDupdateComponent('" + "form" + "', this );");
alertsButton.setBlockSubmit(true);
alertsButton.setImmediate(true);
alertsButton.addActionListener(this);
link.getChildren().add(alertsButton);
cell = new DataTableCell();
cell.setType(CellType.DATA);
cell.setFormat(new Format(Format.CENTER));
cell.addElement(link);
headerRow.addElement(cell);
When this button is clicked it calls processAction() in which I instantiate the HttpServletResponse used to pass in to the working method.
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/octet-stream");
HomeController homeController = (HomeController) context.getApplication().createValueBinding("#{HomeController}").getValue(context);
homeController.createExportFile(response);
EDIT: Adding the createExportFile method with lots taken out for readability.
EDIT2: I've changed the createExportFile so that no HttpServletResponse needs to be passed in. This way the method doesn't have any dependencies on passed in parameters. Both of the buttons (the one with the img and the one that is the CommandButton) call this method and run through without errors in the exact same method. Only the img button creates the excel file though.
public void createExportFile()
throws IOException, PersistenceException, SQLException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse resp = (HttpServletResponse) context.getExternalContext().getResponse();
resp.setContentType("application/octet-stream");
resp.setContentLength(500 * this.getWorkAllDivDeptList().size());
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ "AllDivTeam.csv" + "\""); Map<String, HashSet<String>> stateDateMap = new HashMap<String, HashSet<String>>();
ArrayList<DynamicFieldInfo> txtFieldAllList = new ArrayList<DynamicFieldInfo>();
RequestReader kanbanReader;
try {
//Get all of the data from the DB
} catch (MidTierException mte) {
mte.printStackTrace();
}
String rowTxt = getExportRowHdrTxt(txtFieldAllList, addlColCnt);
response.getOutputStream().write(rowTxt.getBytes(), 0, rowTxt.length());
kanbanReader = new RequestReader("");
for (AllActiveWorkListInfo bwi : (ArrayList<AllActiveWorkListInfo>) this
.getFilteredAllDivDeptList()) {
HashSet<String> set = (HashSet<String>) stateDateMap.get(bwi.getMID());
if (null != set && !set.isEmpty()) {
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
rowTxt = getExportRowTxt(bwi, txtFieldAllList,
kanbanReader, (String) itr.next());
response.getOutputStream().write(rowTxt.getBytes(), 0,
rowTxt.length());
}
} else {
rowTxt = getExportRowTxt(bwi, txtFieldAllList, kanbanReader, "");
response.getOutputStream().write(rowTxt.getBytes(), 0,
rowTxt.length());
}
if (count++ == 200) {
response.getOutputStream().flush();
}
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
Adding Headers:
(Request-Line) POST /kanban/faces/kanbanRepAllDivDeptTickets HTTP/1.1
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-us
Cache-Control no-cache
Connection Keep-Alive
Content-Length 530
Content-Type application/x-www-form-urlencoded
Cookie _cbdModemCheck=false; JSESSIONID=08ADA3D60982F9D13478AF729D6E5205; s_fid=24245A567AE4BB33-0F8E3B5CF3FBEED7
Host localhost:8080
Referer http://localhost:8080/kanban/faces/kanbanRepAllDivDeptTickets
User-Agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
When I debug it goes through all of the process to create the csv exactly like when called from doGet but it never opens the dialog to download or cancel. It's throwing no exceptions and I'm completely out of ideas.
Does anyone see where I'm making an incorrect assumption?
Thanks for your time,
Mike
You are no where writing the file to the output stream. You should write your file to the output stream for that.
This is the sample code worked for me. Hope it helps you.
int BUFSIZE = 4096;
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
String mimeType = "text/csv";
response.setContentType(mimeType);
response.setContentLength((int)document.length());
String documentName = document.getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + yourCsvFileName + "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(document));
while((null != in) && ((length = in.read(byteBuffer)) != -1)) {
outStream.write(byteBuffer, 0, length);
}
in.close();
outStream.close();

How to base.RequestContext.ToOptimizedResultUsingCache() return string for Accept-Encoding: deflate?

I do have following code...
and Accept-Encoding: deflate
public object Get(DTOs.Product request)
{
...
var sCache = base.RequestContext.ToOptimizedResultUsingCache(
this.CacheClient, cacheKey, expireInTimespan, () =>
{
// Business layer returns resultant dataset as XmlDocument
...
return sXML.InnerXml;
});
//returns ServiceStack.Common.Web.HttpResult;
return GenerateResp(sCache, base.Request.Headers["Accept"]);
}
Issue is base.RequestContext.ToOptimizedResultUsingCache returns ServiceStack.Common.Web.CompressedResult even though I am returning XML. I understand that Accept-Encoding: deflate causes RequestContext.CompressionType to deflate.
Above code works fine, when there is no Accept-Encoding (through fiddler test).
But, if the request comes from a browser, it would come as a Compressed, in this case how can I get sCache as string to pass it to GenerateResp?
Thanks for your help.
I am able to resolve the issue by modifying code to...
public object Get(DTOs.Product request)
{
...
var objCache = base.RequestContext.ToOptimizedResultUsingCache(
this.CacheClient, cacheKey, expireInTimespan, () =>
{
// Business layer returns resultant dataset as XmlDocument
...
return sXML.InnerXml;
});
string compressionType = base.RequestContext.CompressionType;
bool doCompression = compressionType != null;
string transformed = "";
if (doCompression)
{
byte[] bCache = ((ServiceStack.Common.Web.CompressedResult)(objCache)).Contents;
transformed = bCache.Decompress(base.RequestContext.CompressionType);
}
else
{
transformed = (string)objCache;
}
//returns ServiceStack.Common.Web.HttpResult;
//In GenerateResp, If compressionType contains "gzip" or "deflate", I compress back the response to respective compression, and add respective Content-Encoding to the header.
return GenerateResp(transformed, base.Request.Headers["Accept"], compressionType);
}
Thank you.

WCat throwing error from ubr file generated from WCat Scenario Creator

I used the WCat Scenario Creator (http://fiddler2wcat.codeplex.com/) to generate the scripts of many requests through a website.
I had to add the "port:8888;" to every request. Then, after the "All clients connected, Test beginning." response, the test produced this error:
Invalid code received.
Error accepting remote connection.
I knew the first two requests worked so it was an issue with what was wrong with the next, 3rd, request.
The request looked like
request {
id = "3";
url = "/Content/Telerik-Kendo/textures/highlight.png";
verb = GET;
cookies = True;
secure = False;
statuscode = 304;
setheader {
name = "Accept";
value = "image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";
}
setheader {
name = "Referer";
value = "http://server.compute-1.amazonaws.com:8888/Home/Winpoints/?sessionid=502hhfoij5ef4jedzouxz02z&low=0&high=150&companyid=3&verticalmarketid=8";
}
setheader {
name = "Accept-Language";
value = "en-US";
}
setheader {
name = "User-Agent";
value = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
}
setheader {
name = "Accept-Encoding";
value = "gzip, deflate";
}
setheader {
name = "Host";
value = "server.compute-1.amazonaws.com:8888";
}
setheader {
name = "If-Modified-Since";
value = "Thu, 27 Sep 2012 05:47:46 GMT";
}
setheader {
name = "If-None-Match";
value = ""0ed9e9e739ccd1:0"";
}
setheader {
name = "Connection";
value = "Keep-Alive";
}
setheader {
name = "Cookie";
value = "ASP.NET_SessionId=502hhfoij5ef4jedzouxz02z";
}
}
The answer, at least for this problem was the double quotes around the value of the "If-None-Match" header.
setheader {
name = "If-None-Match";
value = ""0ed9e9e739ccd1:0"";
}
Changing this to have 1 opening and closing double quote fixed it.
setheader {
name = "If-None-Match";
value = "0ed9e9e739ccd1:0";
}

Resources