如何发布此类格式
{
"Authentication": {
"Username": "testUser@123",
"Password": "testPassword@123"
},
"FileID": "2",
"RequestType": 5
}
我知道如何在objective-c中将这种格式发布到json,这是我的代码
NSURL *url=[NSURL URLWithString:@"http://adservicedev.azurewebsites.net/order/json/process"];
dict = @{@"Authentication":@{@"Username":@"testUser@123",@"Password":@"testPassword@123"},@"RequestType":[NSNumber numberWithInt:4]};
if([NSJSONSerialization isValidJSONObject:dict])
{
__jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
__jsonString = [[NSString alloc]initWithData:__jsonData encoding:NSUTF8StringEncoding];
NSLog(@"Error %@", __jsonString);
}
// Be sure to properly escape your url string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: __jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[__jsonData length]] forHTTPHeaderField:@"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
但是对于快速语言来说是新手,如何在swift中写同样的内容。请帮帮我。
提前致谢
答案 0 :(得分:-1)
那就是你需要实施的方式。
Swift代码
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/php/index.php")!)
request.HTTPMethod = "GET"
let postString = "" // if you want to pass some string to the url you can also do it here i.e type=user now on php side you can get the value by using $_GET['type'] or $_REQUEST['type']
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var FileID : NSString = jsonResult["FileID"]! as NSString
var RequestType : NSString = jsonResult["RequestType"]! as NSString
let Auth : AnyObject = jsonResult["Authentication"]!
var Username : NSString = Auth["Username"]! as NSString
var Password : NSString = Auth["Password"]! as NSString
println("Username : \(Username)")
println("Password : \(Password)")
println("RequestType : \(RequestType)")
println("FileID : \(FileID)")
println("Auth : \(Auth)")
}
task.resume()
PHP代码(index.php)
<?php
$v = '{"Authentication": {"Username": "testUser@123","Password": "testPassword@123" },"FileID": "2","RequestType": 5}';
echo $v;
?>
最终输出