如何在iPhone中实现HTTP Post作为android HTTPPost?

时间:2012-09-14 11:45:14

标签: iphone objective-c http-post nsurlconnection nsurlrequest

我有使用POST方法在HTTTP restful web服务上将密钥对值作为数组列表发送的示例代码。

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中实现相同功能。 任何想法都赞赏...

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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