iOS设备可以发送PUT请求到Rails应用?(Can iOS devices send PUT r

2019-06-25 07:14发布

我们试过很多次发送更新PUT请求到我们的Rails服务器,我们不断收到404“你要找的人是不存在的页面”

我们更新的方法很简单(实际上是通用轨)。

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设备发送PUT请求使用NSURLConnection的服务器或这是没有实现?

更新::

这不更新数据库

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];

Answer 1:

您可以使NSMutableURLRequest并设置HTTP方法:

- (void)setHTTPMethod:(NSString *)method

给它的字符串@"PUT"

这里是你如何创建这样的请求的NSURLConnection的。

NSMutableURLRequest *myMutableRequest[[NSMutableURLRequest alloc] initWithURL:myURL];
[myMutableRequest setHTTPMethod:@"PUT"];
[NSURLConnection connectionWithRequest:myMutableRequest delegate:myDelegate];


Answer 2:

其实@ akshay1188有一个可行的解决方案,但我认为,更好的方法是将“应用程序/ x-WWW的形式,进行了urlencoded”内容类型添加到请求:

[request setHTTPMethod:@"PUT"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];


Answer 3:

设置HTTP方法类型为@“POST”

并添加参数请求体为:@“PUT”关键@“_法”

它应该工作。



文章来源: Can iOS devices send PUT requests to Rails apps?