我试图在NSURLCconnection
中使用POST
在服务器上发布登录信息。我必须设置两个键值对作为emailIdSignIn:abc@def.com
和passwordSignIn:xxxxxxx
。但问题是,我只得到服务器上的emailIdSignIn
值和emailIdSignIn
字段中附加的passwordSignIn
值,passwordSignIn
为nil。我也尝试过NSDictionary
,但在这种情况下,在两个领域都获得null
。我不能更改服务器端代码。这是我的密码客户端
/* initiating request with the url */
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.2:8080/referamaid/app/noauth/serviceconsumer/login"]];
NSString *loginData = [NSString stringWithFormat:@"emailIdSignIn=%@,passwordSignIn=%@",[self.emailTextField text],[self.passwordTextField text],nil];
NSLog(@"login data = %@", loginData);
NSData *postData = [loginData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSError *error;
NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
/* specify the request type */
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
/* set the data to be posted on server into body for "POST"*/
[request setHTTPBody:postData];
NSLog(@"posted data = %@", postData);
/* inititate connection between app and server*/
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
if(!connection)
{
// Release the receivedData object.
receivedData = nil;
// Inform the user that the connection failed.
}
}
}
服务器端代码
@RequestMapping(value = "noauth/serviceconsumer/login" , method=RequestMethod.POST)
public String noAuthScLogin(HttpServletRequest request) {
String retVal = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
userAgent = request.getHeader("User-Agent");
String emailId = request.getParameter("emailIdSignIn");
String password = request.getParameter("passwordSignIn");
}
}
From Wiki:
当web浏览器从web表单元素发送POST请求时默认的互联网媒体类型是"application/x-www-form-urlencoded"。[8]这是一种编码可能重复的键值对的格式钥匙。每个键值对由'&'字符分隔,并且每个键与它的值之间用'='字符分隔。键和值都通过用'+'字符替换空格来转义,然后在所有其他非字母数字[9]字符上使用URL编码。
所以你需要使用&
字符而不是,
:
NSString *loginData = [NSString stringWithFormat:@"emailIdSignIn=%@&passwordSignIn=%@",[self.emailTextField text],[self.passwordTextField text]];