iOS设备可以向Rails应用程序发送PUT请求吗?
我们已经多次尝试向我们的Rails服务器发送更新PUT请求,并且我们一直收到404“您正在寻找的页面不存在”
我们的更新方法非常简单(实际上是通用的rails)。
def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @user.errors, status: :unprocessable_entity } end end
结束
当我从命令行运行CURL来测试更新方法时,它工作正常。 但是,当我在objective-c中尝试相同的方法时,它总是会导致404错误。
所以我的问题是:iOS设备可以使用NSURLConnection向服务器发送PUT请求还是未实现?
更新::
这不会更新数据库
NSString *dataString = @"user[first_name]=bob"; NSData *postBodyData = [NSData dataWithBytes: [dataString UTF8String] length:[dataString length]]; NSString *urlString = [NSString stringWithFormat:@"example.com/users/1.json"]; NSURL *fullURL = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fullURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20]; [request setHTTPMethod: @"PUT"]; [request setHTTPBody:postBodyData]; self.todoConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; receivedData = [NSMutableData data];
这会更新数据库
NSString *urlString = [NSString stringWithFormat:@"example.com/users/1.json?user[first_name]=bob"]; NSURL *fullURL = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fullURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20]; [request setHTTPMethod: @"PUT"]; self.todoConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; receivedData = [NSMutableData data];
您可以创建NSMutableURLRequest并设置HTTP方法:
- (void)setHTTPMethod:(NSString *)method
给它字符串@"PUT"
。
以下是如何从这样的请求创建NSURLConnection。
NSMutableURLRequest *myMutableRequest[[NSMutableURLRequest alloc] initWithURL:myURL]; [myMutableRequest setHTTPMethod:@"PUT"]; [NSURLConnection connectionWithRequest:myMutableRequest delegate:myDelegate];
实际上@ akshay1188有一个可行的解决方案,但我认为更优雅的方法是在请求中添加“application / x-www-form-urlencoded”内容类型:
[request setHTTPMethod:@"PUT"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
将HTTP方法类型设置为@“POST”
并将一个参数添加到请求正文中:@“PUT”表示键@“_方法”
它应该工作。