2012-09-14 57 views
0

我有示例代码使用POST方法将密钥对值作为数组列表发送到HTTTP restful web服务,如下所示。如何在iPhone中实现HTTP Post作为android HTTPPost?

public void postData() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

如何在iPhone中实现相同的Objective-C。 任何想法赞赏...

+1

阅读['NSURLRequest']的文档(https://developer.apple.com/library/iOS/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html)或使用简单包装像[AFNetworking](https://github.com/AFNetworking/AFNetworking) – rckoenes

+0

可能的重复:http://stackoverflow.com/questions/3566516/simple-http-post-example-in-xcode – Mazyod

回答

0

包含JSON库在你的项目,你需要键值对分解成JSON片段,然后通过POST发送..

NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
               @"12345",@"id", 
               @"Hi",@"stringData", 
               ,nil]; 




      //Pass it twice to escape quotes 
      NSString *jsonString = [NSString stringWithFormat:@"%@", [dictionary JSONFragment], nil]; 
      NSString *requestString = [NSString stringWithFormat:@"%@",jsonString,nil]; 
      NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; 
      NSString *urlstr=[NSString stringWithFormat:@"your URL"]; 

      str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
      NSURL *url=[NSURL URLWithString:str]; 

      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
      NSURLResponse *response = nil; 
      NSError *error = nil; 

      NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; 
      [request setHTTPMethod: @"POST"]; 
      [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
      [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
      [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
      [request setHTTPBody: requestData]; 

      NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error ]; 
      NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding]; 

    NSLog(@"your response %@",returnString); 
+0

它不为我工作。 –

0

我写了一个体面的网络客户,欢迎您使用。它使用AFNetworking进行处理并且工作得很好。看看HERE