I would like to do the following in php :
setcookie('name', $value, $Cookie_Expiration,'/');
then some action
header("location:http://www.example.com")
the problem is that I get :
warning: Cannot modify header information - headers already sent by (...etc )
could you please let me know what i am doing wrong and if there is a way to do this?
by the way , this code is before any output is made ...the cookie setting part works fine on its own and so does the redirection code....the combination fails
thank you
How to create a .BAT file to download and unpack a zip file from HTTP server?
We have links like http://example.com/folder.zip and absolute folder link like C:\Users\UserName\Some mixed ??????? English Adress\
if files from zip exist in directory owerrite them.
using only native windows (xp vista win7 etc) BAT functions and files.
Could you add code example, please.
I'm using launching firefox from the command line in a script to get snapshots of pages. These pages have basic http authentication. When using:
firefox http://user:[email protected]
Either a dialog appears, or authentication doesn't work at all.
Is there any option to make firefox open the page without showing the dialog?
I can set any other headers but not "Date". request.setRequestHeader("hi", "world"); works but request.setRequestHeader("Date", "today"); does not. That is in Opera.
I have an ubuntu 10.04 server where I installed mod_evasive using apt-get install libapache2-mod-evasive
I already tried several configurations, the result stays the same.
The blocking does work, but randomly.
I tried with low limis and long blocking periods as well as short limits.
The behaviour I expect is that I can request websites until either page or site limit is reached per given interval.
After that I expect to be blocked until I did not make another request for as long as the block period.
However the behaviour is that I can request sites and after a while I get random 403 blocks, which increase and decrase in percentage, however they are very scattered.
This is an output of siege, so you get an idea:
HTTP/1.1 200 0.09 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.11 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.09 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.09 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.09 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.10 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.08 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.09 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.10 secs: 75 bytes ==> /robots.txt
HTTP/1.1 403 0.09 secs: 242 bytes ==> /robots.txt
HTTP/1.1 200 0.09 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.09 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.10 secs: 75 bytes ==> /robots.txt
HTTP/1.1 200 0.08 secs: 75 bytes ==> /robots.txt
The exac limits in place during this test run were:
DOSHashTableSize 3097
DOSPageCount 10
DOSSiteCount 100
DOSPageInterval 10
DOSSiteInterval 10
DOSBlockingPeriod 120
DOSLogDir /var/log/mod_evasive
DOSEmailNotify ***@gmail.com
DOSWhitelist 127.0.0.1
So I would expect to be blocked at least 120 seconds after being blocked once.
Any ideas aobut this?
I also tried adding my configuration at different places (vhost, server config, directory context) and with of without ifmodule directive...
This doesnt change anything.
I have a magento site and i need to have it redirect to https, i have the cert installed but i am not sure how to mod the htaccess file?
here is a copy of the root htaccess file
thanks
#
uncomment these lines for CGI mode
make sure to specify the correct cgi php binary file name
it might be /cgi-bin/php-cgi
Action php5-cgi /cgi-bin/php5-cgi
AddHandler php5-cgi .php
#
GoDaddy specific options
Options -MultiViews
you might also need to add this line to php.ini
cgi.fix_pathinfo = 1
if it still doesn't work, rename php.ini to php5.ini
#
this line is specific for 1and1 hosting
#AddType x-mapp-php5 .php
#AddHandler x-mapp-php5 .php
#
default index file
DirectoryIndex index.php
#
adjust memory limit
php_value memory_limit 64M
php_value memory_limit 128M
php_value max_execution_time 18000
#
disable magic quotes for php request vars
php_flag magic_quotes_gpc off
#
disable automatic session start
before autoload was initialized
php_flag session.auto_start off
#
enable resulting html compression
#php_flag zlib.output_compression on
#
disable user agent verification to not break multiple image upload
php_flag suhosin.session.cryptua off
#
turn off compatibility with PHP4 when dealing with objects
php_flag zend.ze1_compatibility_mode Off
#
disable POST processing to not break multiple image upload
SecFilterEngine Off
SecFilterScanPOST Off
#
# Insert filter on all content
###SetOutputFilter DEFLATE
# Insert filter on selected content types only
#AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
# Netscape 4.x has some problems...
#BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
#BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
#BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
#SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
#Header append Vary User-Agent env=!dont-vary
#
make HTTPS env vars available for CGI mode
SSLOptions StdEnvVars
#
enable rewrites
Options +FollowSymLinks
RewriteEngine on
#
you can put here your magento root folder
path relative to web root
#RewriteBase /magento/
#
workaround for HTTP authorization
in CGI environment
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
always send 404 on missing files in these folders
RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
#
never rewrite for existing files, directories and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
#
rewrite everything else to index.php
RewriteRule .* index.php [L]
#
Prevent character encoding issues from server overrides
If you still have problems, use the second line instead
AddDefaultCharset Off
#AddDefaultCharset UTF-8
#
s
ExpiresDefault "access plus 1 year"
#
By default allow all access
Order allow,deny
Allow from all
I am using JAXB to create XML file from a result set.
I have created java/ /class files using the xsd with the help of xjc utiliy. Now I am trying to create the xml file using the Marshaller. In the XML file I do not see theh xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" attribute with the root tag. My xsd
Below is the code :
public class JAXBConstructor
{
public void generateXMLDocument(File xmlDocument){
try
{
JAXBContext jaxbContext = JAXBContext.newInstance("com");
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
com.ObjectFactory factory = new com.ObjectFactory();
USERTASKSImpl userTasks =(USERTASKSImpl)(factory.createUSERTASKS());
USERTASKTypeImpl userTaskType = (USERTASKTypeImpl)(factory.createUSERTASKSTypeUSERTASKType());
userTaskType.setName("zmannan");
userTaskType.setCode("G5023920");
java.util.List userTaskList=userTasks.getUSERTASK();
userTaskList.add(userTaskType);
marshaller.marshal(userTasks, new FileOutputStream("User_Task.xml"));
}
Output of the code : This does not contain the XMLSchema value -
< ?xml version="1.0" encoding="UTF-8" standalone="yes"?
< USER_TASKS xmlns="http://schemas.jpmchase.net/Recertification"
< CodeG5023920< /Code
< Namezmannan< /Name
< /USER_TASK
< /USER_TASKS
Please help how can I add the schema-instance value in the rrot tag.
I am currently uploading images to my server via HTTP POST. Everything works fine using the code below.
NSString *UDID = md5([UIDevice currentDevice].uniqueIdentifier);
NSString *filename = [NSString stringWithFormat:@"%@-%@", UDID, [NSDate date]];
NSString *urlString = @"http://taptation.com/stationary_data/index.php";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:imageData]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
However, when I try to convert this to work with Image Shacks XML API, it doesn't return anything. The directions from ImageShack are below.
Send the following variables via POST to imageshack. us /index.php
fileupload; (the image)
xml = "yes"; (specifies the return of XML)
cookie; (registration code, optional)
Does anyone know where I should go from here?
I have the following code:
...
sub setImage {
my $self=shift;
my $filename=shift;
unless(-r $filename) {
warn "File $filename not found";
return;
}
my $imgn=shift;
my $operation=&URI::Escape::uri_escape_utf8(
(shift) ? "???????! (Delete)" : "?????????! (Store)");
my $FH=&::File::open($filename, 0, 0);
my $image;
# &utf8::downgrade($image);
sysread($FH, $image, 102400, 0);
close $FH;
my $imginfo=eval{&Image::Info::image_info(\$image)};
if($@ or $imginfo->{"error"}) {
warn "Invalid image: ".($@ || $imginfo->{"error"});
return undef;
}
my $fields=[
DIR => $self->url("fl"),
OPERATION => $operation,
FILE_NAME => ".photo$imgn",
# FILE => [$filename],
FILE => [undef, "image.".$imginfo->{"file_ext"},
# Content_Type => $imginfo->{"file_media_type"},
# Content_Type => 'application/octet-stream',
Content => $image,
],
];
my $response=&ZLR::UA::post(
&ZLR::UA::absURL("/cgi-bin/file_manager")."",
$fields,
Content_Type => "form-data",
);
print $response->decoded_content;
}
...
When I try to use function setImage it fails with error HTTP::Message content must be bytes at /usr/lib64/perl5/vendor_perl/5.8.8/HTTP/Request/Common.pm line 91. Worse that I can't reproduce this error without using all of my code and upgrading libwww-perl does nothing. What can cause it?
I am calling a server method through HTTPService from client side. The server is a RestFul web service and it might respond with one of many HTTP error codes (say, 400 for one error, 404 for another and 409 for yet another). I have been trying to find out the way to determine what was the exact error code sent by the server. I have walked teh entire object tree for the FaultEvent populated in my fault handler, but no where does it tell me the error code. Is this missing functionality in Flex?
My code looks like this:
The HTTP Service declaration:
<mx:HTTPService id="myServerCall" url="myService" method="GET"
resultFormat="e4x" result="myServerCallCallBack(event)" fault="faultHandler(event)">
<mx:request>
<action>myServerCall</action>
<docId>{m_sDocId}</docId>
</mx:request>
</mx:HTTPService>
My fault handler code is like so:
private function faultHandler(event : FaultEvent):void
{
Alert.show(event.statusCode.toString() + " / " + event.fault.message.toString());
}
I created and deployed a pretty simple WCF Service. but when accessing it from IE, I get this :
HTTP Error 500.19 - Internal Server Error
Description: The requested page cannot be accessed because the related configuration
data for the page is invalid.
Error Code: 0x80070005
Notification: BeginRequest
Module: IIS Web Core
Requested URL: http://localhost:80/ProductsService/ProductsService.svc
Physical Path: C:\Users\Administrator\Documents\Visual Studio 2008\Projects\ProductsService\ProductsService\ProductsService.svc
Logon User: Not yet determined
Logon Method: Not yet determined
Handler: Not yet determined
Config Error: Cannot read configuration file
Config File: \\?\C:\Users\Administrator\Documents\Visual Studio 2008\Projects \ProductsService\ProductsService\web.config
Config Source: -1:
0:
More Information... This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error.
here is the content of my web.config file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<dataConfiguration defaultDatabase="AdventureWorksConnection" />
<connectionStrings>
<add name="AdventureWorksConnection" connectionString="Database=AdventureWorks; Server=(localhost)\SQLEXPRESS;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.serviceModel>
<services>
<service name="Products.ProductsService">
<endpoint address=""
binding="basicHttpBinding"
contract="Products.IProductsService" />
</service>
</services>
</system.serviceModel>
</configuration>
Hey,
I have an HTTP Module that I use to clean up the JSON returned by my web service (see http://www.codeproject.com/KB/webservices/ASPNET_JSONP.aspx?msg=3400287#xx3400287xx for an example of this.) Basically it relates to calling cross-domain JSON web services from javascript.
There is this JsonHttpModule which uses a JsonResponseFilter Stream class to write out the JSON and the overloaded Write method is supposed to wrap the name of the callback function around the JSON, otherwise the JSON errors out as needing a label. However, if the JSON is really long, the Write method in the Stream class is called multiple times, causing the callback function to incorrectly get inserted midway through the JSON. Is there a way in the Stream class to wrap the callback function around the stream at the end or to specify that it write all of the JSON in 1 Write method instead of in chunks??
Here's where it calls the JsonResponseFilter in the JsonHttpModule:
public void OnReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (!_Apply(app.Context.Request)) return;
// apply response filter to conform to JSONP
app.Context.Response.Filter =
new JsonResponseFilter(app.Context.Response.Filter, app.Context);
}
Here's the Write method in the JsonResponseFilter Stream class that gets called multiple times:
public override void Write(byte[] buffer, int offset, int count)
{
var b1 = Encoding.UTF8.GetBytes(_context.Request.Params["callback"] + "(");
_responseStream.Write(b1, 0, b1.Length);
_responseStream.Write(buffer, offset, count);
var b2 = Encoding.UTF8.GetBytes(");");
_responseStream.Write(b2, 0, b2.Length);
}
Thanks for any help!
Justin
I implemented an HTTP client is iOS that is meant to be a singleton. It is a subclass of AFNetworking's excellent AFHTTPClient
My access method is pretty standard:
+ (LBHTTPClient*) sharedHTTPClient
{
static dispatch_once_t once = 0;
static LBHTTPClient *sharedHTTPClient = nil;
dispatch_once(&once, ^{
sharedHTTPClient = [[LBHTTPClient alloc] initHTTPClient];
});
return sharedHTTPClient;
}
// my init method
- (id) initHTTPClient
{
self = [super initWithBaseURL:[NSURL URLWithString:kBaseURL]];
if (self)
{
// Sub class specific initializations
}
return self;
}
Super's init method is very long, and can be found here
However the problem I experience is when the dispatch_once queue is run, the app locks and become unresponsive.
When I step through code, I notice that it locks on dispatch_once and then remains frozen. Is this something to do with the main thread locking down? How come it stays locked like that?
Also, none of the HTTP client methods fire.
Stepping through the code some more, I find this line in dispatch/once.h is where the app locks down:
DISPATCH_INLINE DISPATCH_ALWAYS_INLINE DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void
_dispatch_once(dispatch_once_t *predicate, dispatch_block_t block)
{
if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) {
dispatch_once(predicate, block); // App locks here
}
}
Here is my MVC Controller and everything is fine:
private UnitOfWork UOW;
public InventoryController()
{
UOW = new UnitOfWork();
}
// GET: /Inventory/
public ActionResult Index()
{
var products = UOW.ProductRepository.GetAll().ToList();
return View(products);
}
Same method call in API Controller gives me an Http 500 Error:
private UnitOfWork _unitOfWork;
public TestController()
{
_unitOfWork = new UnitOfWork();
}
public IEnumerable<Product> Get()
{
var products = _unitOfWork.ProductRepository.GetAll().ToList();
return products;
}
Debugging shows that indeed there is data being returned in both controllers' UOW calls. I then added a customer configuration in Global:
public static void CustomizeConfig(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.XmlFormatter);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
I am still receiving an Http 500 in API Controller ONLY and at a loss as to why. Any ideas?
UPDATE:
It appears using lazy loading caused the problem. When I set the associated properties to NON-VIRTUAL the Test API provided the necessary JSON string. However, whereas before I had the Vendor class included, I only have VendorId. I really wanted to included the associated classes. Any ideas? I know there are alot of smart people out there. Anyone?
I am looking to send a very long String, which is an image that is encoded into a String. I need to send that information using POST method. I have implemented the same in Android using key-value pair, I need to implement the same in iOS using key-value pair. Please help me with useful resources/approach.
EDIT 1
What have I tried
[dictionnary setObject:@"admin" forKey:@"username"];
[dictionnary setObject:@"123123" forKey:@"password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = @"MY CALL URL";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSLog(@"response is obtained");
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(@"%@", responseString);
EDIT 2
Error I am getting
Request Error Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0x7ba0120 {NSErrorFailingURLKey=http://yahoo.com/, NSErrorFailingURLStringKey=http://yahoo.com/}
Hi, I'm writing a very simple testing framework for my application, the design isn't perfect, but I don't have time to write something more complex.
Essentially, I have a client and server-application, on my server I want a small python web server to start the server application with given test sequences on a GET or POST call. Also, the application prints some testdata to stderr which I'd like to catch and return in another HTTP call. At the moment I have this:
from subprocess import Popen, PIPE
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
p = None
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
global p
if self.path.endswith("start/"):
p = Popen(["./bin/Release/simplex264","BBB-360","127.0.0.1"], stderr=PIPE)
print 'started'
return
elif self.path.endswith("getResults/"):
self.wfile.write(p.stderr.read())
return
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
server = HTTPServer(('localhost', 9876), MyHandler)
print 'Started server...'
server.serve_forever()
except KeyboardInterrupt:
print 'Shutting down...'
server.socket.close()
if __name__ == '__main__':
main()
Which 'works', except for one part, when I try to open http://localhost:9876/start/, it does not return before the process ended. However, the 'started' appears in my shell immediately (I added this because I thought the Popen call would only return after execution). I do not know the perfect inner workings of Popen and BaseHTTPRequestHandler however and do not really know where it goes wrong. Is there any way to make this work asynchronously?
Hi,
I am trying to develop a java http client with apache httpcomponents 4.0.1. This client calls the page "https://myHost/myPage". This page is protected on the server by a JNDIRealm with a login form authentication, so when I try to get https://myHost/myPage I get a login page. I tried to bypass it unsuccessfully with the following code :
//I set my proxy
HttpHost proxy = new HttpHost("myProxyHost", myProxyPort);
//I add supported schemes
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
supportedSchemes.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// prepare parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
//I add my authentication information
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("myHost/myPage", 443),
new UsernamePasswordCredentials("username", "password"));
HttpHost host = new HttpHost("myHost", 443, "https");
HttpGet req = new HttpGet("/myPage");
//show the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String rsp = httpClient.execute(host, req, responseHandler);
System.out.println(rsp);
When I run this code, I always get the login page, not myPage. How can I apply my credential parameters to avoid this login form?
Any help would be fantastic
I have a feature in my Rials app that works just fine with the message "Responds to browser_basic_authorize" from the Background Given step.
However, if I add a @javascript tag before the scenario, then my Background Given fails with "I don't know how to login".
What's going wrong and how do I go about testing javascrpt interactions on my app?
Background:
Given I perform HTTP authentication as "<id>/<password>"
When I go to the homepage
Then I should see "Text-that-you-should-see-on-your-home-page"
Scenario: Displaying injury causative factors
Given I am on the new_incident_report page
When I choose "incident_report_employee_following_procedures_true"
Then I should see "Equipment failure?"
Then I should not see "Lack of training"
When /^I perform HTTP authentication as "([^\"]*)\/([^\"]*)"$/ do |username, password|
puts "id/pswd: #{username}/#{password}"
### Following works ONLY if performed first before even going to a page!!!
if page.driver.respond_to?(:basic_auth)
puts 'Responds to basic_auth'
page.driver.basic_auth(username, password)
elsif page.driver.respond_to?(:basic_authorize)
puts 'Responds to basic_authorize'
page.driver.basic_authorize(username, password)
elsif page.driver.respond_to?(:browser) && page.driver.browser.respond_to?(:basic_authorize)
puts 'Responds to browser_basic_authorize'
page.driver.browser.basic_authorize(username, password)
else
raise "I don't know how to log in!"
end
end
Rails 3.0.9, current gems, other tests passing.
Hi,
I am in need of a scalable and performant HTTP application/server that will be used for static file serving/uploading. So I only need support for GET and PUT operations.
However, there are a few extra features that I need:
Custom authentication: I need to
check credentials against a database for each request.
Thus I must be able to integrate propietary
database interaction.
Support for
signed access keys: The access to
resources via PUT should be signed
using a key like http://uri/?key=foo The key then contains information about the request like md5(user + path + secret) which allows me to block unwanted requests. The application/server should allow me to check for this.
Performance: I'd like to avoid piping content as much as possible. Otherwise the whole application could be implemented in Perl/etc. in a few lines as CGI.
Perlbal (in webserver mode) looks nice, however the single-threaded model does not fit with my database lookup and it does also not support query strings.
Lighttp/Nginx/… have some modules for these tasks, however it is not feasible putting everything together without ending up writing own extensions/modules.
So how would you solve this? Are there other leightweight webservers available for this?
Should I implement an application inside of a webserver (i.e. CGI). How can I avoid/speed up piping content between the webserver and my application.
Thanks in advance!
i have a problem with a http post call in firefox. I know that when there are a cross origin, firefox first do a OPTIONS before the POST to know the access-control-allow headers.
With this code i dont have any problem:
Net.requestSpeech.prototype.post = function(url, data) {
if(this.xhr != null) {
this.xhr.open("POST", url);
this.xhr.onreadystatechange = Net.requestSpeech.eventFunction;
this.xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
this.xhr.send(data);
}
}
I test this code with a simple html that invokes this function.
Everything is ok and i have the response of the OPTIONS and POST, and i process the response. But, i'm trying to integrate this code with an existen application with uses jquery (i dont know if this is a problem), when the send(data) executes in this case, the browser (firefox) do the same, first do a OPTION request, but in this case dont receive the response of the server and puts this message in console:
[18:48:13.529] OPTIONS http://localhost:8111/ [undefined 31ms]
Undefined... the undefined is because dont receive the response, but the code is the same, i dont know why in this case the option dont receive the response, someone have an idea?
i debug my server app and the OPTIONS arrive ok to the server, but it seems like the browser dont wait to the response.
edit more later: ok i think that the problem is when i run with a simple html with a SCRIPT tag that invokes the method who do the request run ok, but in this app that dont receive the response, i have a form that do a onsubmit event, i think that the submit event returns very fast and the browser dont have time to get the OPTIONS request.
edit more later later: WTF, i resolve the problem make the POST request to sync:
this.xhr.open("POST", url, false);
The submit reponse very quickly and can't wait to the OPTION response of the browser, any idea to this?
I'm coding a .NET library in C# for communicating with XBMC via its JSON RPC interface using HTTP.
I coded and released a preliminary version but everything is done synchronously. I then recoded the library to be asynchronous for my own purposes as I was/am building an XBMC remote for WP7.
I now want to release the new async library but want to make sure it's nice and tidy before I do.
Due to the async nature a user initiates a request, supplies a callback method that matches my delegate and then handles the response once it's been received.
The problem I have is that within the library I track a RequestState object for the lifetime of the request, it contains the http request/response as well as the user callback etc. as member variables, this would be fine if only one type of object was coming back but depending on what the user calls they may be returned a list of songs or a list of movies etc.
My implementation at the moment uses a single delegate ResponseDataRecieved which has a single parameter which is a simple Object - As this has only be used by me I know which methods return what and when I handle the response I cast said object to the type I know it really is - List, List etc.
A third party shouldn't have to do this though - The delegate signature should contain the correct type of object. So then I need a delegate for every type of response data that can be returned to the third party - The specific problem is, how do I handle this gracefully internally - Do I have a bunch of different RequestState objects that each have a different member variable for the different delegates? That doesn't "feel" right. I just don't know how to do this gracefully and cleanly.
Hi,
I am using ifstream to open a file and then read from it.
My program works fine when i give location of the local file
on my system.
for eg
/root/Desktop/abc.xxx works fine
But once the location is on the http server the file fails to
open.
for eg
http://192.168.0.10/abc.xxx fails to open.
Is there any alternate for ifstream when using a URL address?
thanks.
part of the code where having problem:
bool readTillEof = (endIndex == -1) ? true : false;
// Open the file in binary mode and seek to the end to determine file size
ifstream file ( fileName.c_str ( ), ios::in|ios::ate|ios::binary );
if ( file.is_open ( ) )
{
long size = (long) file.tellg ( );
long numBytesRead;
if ( readTillEof )
{
numBytesRead = size - startIndex;
}
else
{
numBytesRead = endIndex - startIndex + 1;
}
// Allocate a new buffer ptr to read in the file data
BufferSptr buf (new Buffer ( numBytesRead ) );
mpStreamingClientEngine->SetResponseBuffer ( nextRequest,
buf );
// Seek to the start index of the byte range
// and read the data
file.seekg ( startIndex, ios::beg );
file.read ( (char *)buf->GetData(), numBytesRead );
// Pass on the data to the SCE
// and signal completion of request
mpStreamingClientEngine->HandleDataReceived( nextRequest,
numBytesRead);
mpStreamingClientEngine->MarkRequestCompleted( nextRequest );
// Close the file
file.close ( );
}
else
{
// Report error to the Streaming Client Engine
// as unable to open file
AHS_ERROR ( ConnectionManager,
" Error while opening file \"%s\"\n",
fileName.c_str ( ) );
mpStreamingClientEngine->HandleRequestFailed( nextRequest,
CONNECTION_FAILED );
}
}
We have a current eCommerce Site that runs on ASP.NET and we hired a consultant to develop an new site bases on SOA. The new site architecture is as follows
Web Application : Single Page Web Application (built on javascript/jquery templates - do not use any MVVM frameworks) that uses some javascript thrown all over the place.
Service Layer : Very very light Service Layer that does not do anything other than calling a single stored procedure and pass in the entire http request.
Database : The entire site content is in the database. The database does the heavy lifting of parsing the request and based on the HTTP method and some input parameter calls the appropriate Store Procedures or views and renders the result in JSON/XML.
We have been told by them that this is built on latest and greatest technologies. I have a lot of concerns and of them given are the few
Load on the Database
SEO concerns for single page application as this is a public facing website
Scalablity?
Is this SOA?
Cross Browser compatability (Site does not work in < IE9)
Realistic implementaion of Single page application
I know something is not right but I just need to validate my concerns here. Please help me.