我试图通过json将数据发布到服务器中。假设我的xib中只有一个名为username的字段。现在我将这些数据发布到服务器中。我写了这段代码 NSString * uname = txt_name.text;
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:@"http://mypath/index.php?params=123"]];
[request setHTTPMethod:@"POST"];
// NSString *postString = @"Email=me@test.com";
[request setValue:[NSString
stringWithFormat:@"%d", [uname length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[uname
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
NSLog(@"text",uname);
但我不知道数据是否发布。我想将输入数据发布到Xcode的控制台中,但没有显示任何内容。是什么原因..?什么是错的......?
答案 0 :(得分:0)
您需要以下请求:
NSDictionary *dataDict = @{@"uname": <YOUR_UNAME>};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://mypath/index.php?params=123"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%d",postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
确保服务器已使用您的数据
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = httpResponse.statusCode;
...........
}
如果成功,您将获得 statusCode = 200。
答案 1 :(得分:0)
NSString *string= [NSString stringWithFormat:@"your Url.php?&Username=%@",username];
NSLog(@"%@",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData: %@", str);
NSString *str1 = @"1";
if ([str isEqualToString:str1 ])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Successfully" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"" delegate:self cancelButtonTitle:@"Try Later" otherButtonTitles:@"Call", nil];
alert.tag = 1;
[alert show];
}
不需要使用JSON就可以在没有JSON的情况下实现这一点!!!