iphone - Http 发布请求

标签 iphone json http

如何使用 JSON 发出 Http Post 请求。我尝试了 Internet 上可用的每个选项。但无法获取数据。因此,请发布完整代码以提出请求。

最佳答案

您可以使用以下代码:


-(void)performRequest{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url"]];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [jsonMessage length]];
    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue: jsonAction forHTTPHeaderField:@"JSONAction"];
    [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: [jsonMessage dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
    [pool release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [webData setLength: 0];
    self.resultArray = [[NSMutableArray alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"ERROR with theConenction");
    NSDictionary *errorDic = [NSDictionary dictionaryWithObject:error forKey:@"error"];
    [self.resultArray addObject:errorDic];
    [connection release];
    [webData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", theXML);
    [theXML release];
    if([webData length] > 0){
        parser = [[NSXMLParser alloc] initWithData:webData];
        [parser setDelegate:self];
        [parser parse]; 
    }
}

关于iphone - Http 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968107/

相关文章:

php - 在 ListView 中显示从 .php 脚本接收到的数据

json - Go语言如何通过调用url获取JSON对象?

iphone: View 隐藏后重新启动循环动画,然后重新出现?

php - 如何在 foreach 中回显从 JSON 到字符串的数组转换

javascript - 请求的 content-type header 包含的内容多于 MIME 类型,为什么?

java - WSO2 ESB 消息上下文无法通过自定义类中介器更改

internet-explorer - 集群服务器上的文件下载 servlet 与 IE 的行为不同

iphone - 了解设备类型——视网膜/非视网膜

ios - Skobbler 建议问题

iphone - 什么触发了 iOS 中的离屏渲染、混合和 layoutSubviews?