我正在尝试使用POST
中的NSURLCconnection
在服务器上发布登录信息。我必须将两个键值对设置为emailIdSignIn:abc@def.com
和passwordSignIn:xxxxxxx
。但问题是,我在服务器上只获得emailIdSignIn
值,passwordSignIn
字段中附加emailIdSignIn
的值,passwordSignIn
为零。我也尝试了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");
}
}
答案 0 :(得分:0)
来自Wiki:
当Web浏览器从Web表单元素发送POST请求时, 默认的互联网媒体类型是" application / x-www-form-urlencoded"。[8] 这是一种用于编码可能重复的键值对的格式 键。每个键值对由'&'分隔开。人物,每个人 通过' ='将键与其值分开。字符。键和值 通过用' +'替换空格来逃避性格然后 在所有其他非字母数字[9]字符上使用URL编码。
因此,您需要使用&
字符而不是,
:
NSString *loginData = [NSString stringWithFormat:@"emailIdSignIn=%@&passwordSignIn=%@",[self.emailTextField text],[self.passwordTextField text]];