views:

3496

answers:

2

My code is like the following:

URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);         
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent", 
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();

Is it ok if I set the headers before I get the InputStream? Will my header be sent, or will the server see the default URLConnection's user-agent ( if any ) ?

+3  A: 

The headers must be set prior to getting the InputStream to have any affect - an IllegalStateException will be thrown if the connection is already open.

As far as the User-Agent header specifically, it should be sent if it has been set.

See the URLConnection JavaDoc.

Ken Gentle
A: 

@interface urlPostMethod: NSObject {

}

-(void) reDirect;

@end

@implementation urlPostMethod

-(void) reDirect{ NSString *post = [NSString stringWithFormat:@"text1=MYNAME"];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

//NSString *postLength = [NSString stringWithFormat:@"",[postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://10.0.0.7:8080/UrlProject/DemoUrl.jsp"]]];

[request setHTTPMethod:@"POST"];

//[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
if(conn)
{
    NSLog(@"Connection Successful");
}
else
{
    NSLog(@"Connection could not be made");
}

}

@end

int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

urlPostMethod* urlPost= [[urlPostMethod alloc]init];    

[urlPost reDirect];

[pool drain];
return 0;

}

Sumit
The question was directed at Java programmers.
Geo