在ios使用http post方法:
NSString *post = @"did=abc&uid=王大明&score=0.3,0.4,0.5,1.1,1.4";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://greenevent2.sunlight.tw/putdata2.asp"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [NSMutableData data];
}
else
{
}
在ios使用http get方法:
NSURL *apiUrl = [NSURL URLWithString:@"http://greenevent2.sunlight.tw/putdata.asp?did=abc&uid=%E7%8E%8B%E5%A4%A7%E6%98%8E&score=0.3,0.4,0.5,1.1,1.4"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL: apiUrl];
[request setHTTPMethod:@"GET"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [NSMutableData data];
}
Delegate方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"response");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
[receivedData appendData:d];
NSLog(@"didReceiveData");
NSString* newStr = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"returnData:%@",newStr);
//NSLog(@"receivedData:%@",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
/*
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
// Do anything you want with it
[responseText release];
*/
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSString *username = @"username";
NSString *password = @"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
同步方式
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];- [request setURL:[NSURL URLWithString:urlStr]];
- [request setHTTPMethod:@"GET"];
- NSData *returnData = [NSURLConnection sendSynchronousRequest:request
- returningResponse:nil error:nil];
- [request release];
沒有留言:
張貼留言