0

我有使用 POST 方法在 HTTP 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 中实现相同的功能。任何想法表示赞赏...

4

2 回答 2

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);
于 2012-09-14T11:54:53.413 回答
0

我写了一个不错的网络客户端,欢迎大家使用。它使用 AFNetworking 进行处理,效果很好。看看这里

于 2012-09-14T12:02:40.990 回答