2013-02-13 213 views
3

我有一个简单的asp.net web服务,它返回json格式的数据。我想用参数发送http post请求来获取json数据。 如何发送请求并获取数据?带参数的Http Post请求

POST请求:

POST /JsonWS.asmx/FirmaGetir HTTP/1.1 
Host: localhost 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 

firID=string 

答案:

HTTP/1.1 200 OK 
Content-Type: text/xml; charset=utf-8 
Content-Length: length  
<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">string</string> 

我尝试了一些代码,但他们没有工作。

NSString *firmadi [email protected]""; 
NSMutableData *response; 


-(IBAction)buttonClick:(id)sender 
{ 
    NSString *firid = [NSString stringWithFormat:@"800"]; 

    response = [[NSMutableData data] retain]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]]; 

    NSString *params = [[NSString alloc] initWithFormat:@"firID=%@",firid]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if(theConnection) 
    { 
     response = [[NSMutableData data] retain]; 

    } 
    else 
    { 
     NSLog(@"theConnection is null"); 
    } 

} 

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed 
{ 
    [response setLength:0]; 
    NSURLResponse * httpResponse; 

    httpResponse = (NSURLResponse *) responsed; 

} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data 
{ 
    [response appendData:data]; 
    //NSLog(@"webdata: %@", data); 

} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error 
{ 
    NSLog(@"error with the connection"); 
    [connection release]; 
    [response release]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 

    response = [[NSMutableData data] retain]; 

NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 

} 
+1

您是否尝试将请求的MIME类型设置为'application/json'而不是'application/x-www-form-urlencoded'? – 2013-02-13 15:40:34

+0

它来自我的网络服务,为什么我改变这个设置? – 2013-02-13 15:43:13

+0

什么不适用于您发布的代码? – 2013-02-13 15:47:55

回答

1

你在这里做什么:

[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

此行返回一个NSURLConnection的,但你是不是存放。这对你无能为力。

你读它之前,你清除数据:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it 
    NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 

} 

编辑

-(IBAction)buttonClick:(id)sender { 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"] 
                  cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
                 timeoutInterval:15]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:[@"firID=800" dataUsingEncoding:NSUTF8StringEncoding]]; 
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [self.connection start]; 

} 


#pragma NSURLConnection Delegates 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 

    if (!self.receivedData){ 
     self.receivedData = [NSMutableData data]; 
    } 
    [self.receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 
} 
+0

感谢您的关注。我新开发ios。因此,我的代码中有一些愚蠢的代码块。我为此提出问题。我会尝试这些,但请写下这个过程的完整代码。 – 2013-02-13 17:13:35

+0

我添加了一个代码示例。 – Jaybit 2013-02-13 17:26:56

+0

谢谢,我明天再试。 – 2013-02-13 22:01:24

0

我今天早上遭遇这个问题,我只是弄清楚了。我猜你的问题的关键是如何使用参数 POST方法。其实,这很简单。

(1)首先,您应该确保您的文件已准备好发送。这里我们说它是一个叫做的字符串,它是一个NSString,字符串准备是。我们在我们的方法postRequest中使用它作为参数(这里不是我们想谈论的HTTP POST参数,不用担心)。

// Send JSON to server 
- (void) postRequest:(NSString *)stringReady{ 
// Create a new NSMutableURLRequest 
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.xxxxxx.io/addcpd.php"]]; 
[req setHTTPMethod:@"POST"]; 

(2)现在,我们就说它是服务器希望得到被称为“数据”的参数,这是如何将你的参数到HTTP体的方式。

// Add the [data] parameter 
NSString *bodyWithPara = [NSString stringWithFormat:@"data=%@",stringReady]; 

看,这是如何使用POST方法添加参数。您只需简单地将该参数放在要发送的文件之前。如果您aleary konw你的参数,那么你就可以更好地检查这个网站:

https://www.hurl.it/

这将帮助你测试,如果你正确地发送文件,它会显示在网页底部的响应。 (3)第三,我们将我们的NSString包装到NSData中并发送给服务器。

// Convert the String to NSData 
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
// Set the content length and http body 
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 
[req addValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[req setHTTPBody:postData]; 
// Create an NSURLSession 
NSURLSession *session = [NSURLSession sharedSession]; 
NSURLSessionDataTask *task = [session dataTaskWithRequest:req 
             completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
              // Do something with response data here - convert to JSON, check if error exists, etc.... 
              if (!data) { 
               NSLog(@"No data returned from the sever, error occured: %@", error); 
               return; 
              } 

              NSLog(@"got the NSData fine. here it is...\n%@\n", data); 
              NSLog(@"next step, deserialising"); 

              NSError *deserr; 
              NSDictionary *responseDict = [NSJSONSerialization 
                      JSONObjectWithData:data 
                      options:kNilOptions 
                      error:&deserr]; 
              NSLog(@"so, here's the responseDict\n\n\n%@\n\n\n", responseDict); 
             }]; 

[task resume];} 

希望这可以帮助有人卡在这里。