IOS 应用程序将数据发送到 REST API 服务内容类型定义错误



我设法制作了一个应用程序来将数据发送到 rest api 服务。内容类型必须是文本/html。但是每当我运行我的应用程序时,我都会收到 415 http 代码响应,这意味着不支持的内容类型。这是我的代码:

NSURL *url = [NSURL new];
NSData *body = nil;
NSString *contentType = @"text/html"; 
NSURL *finalURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://telesto.zapto.org:81/SMART_EdgeNode/EdgeNode/DataFeeds/3/addMeasurement"]];
NSString *yourString = @"geoX#35#geoY#65";


contentType = @"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:@"%@", yourString] dataUsingEncoding:NSUTF8StringEncoding];
NSString *putLength = [NSString stringWithFormat:@"%d",[body length]];

if (nil==finalURL) {
    finalURL = url;
}

NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:@"Content-Type"];
[headers setValue:@"mimeType" forKey:@"Accept"];
[headers setValue:@"no-cache" forKey:@"Cache-Control"];
[headers setValue:@"no-cache" forKey:@"Pragma"];
[headers setValue:@"close" forKey:@"Connection"];



NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
[request setHTTPMethod:@"PUT"];
[request setAllHTTPHeaderFields:headers];

[request setHTTPBody:body];
[request setValue:putLength forHTTPHeaderField:@"Content-Length"];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

我想 atm 定义内容类型有问题.有什么帮助吗??

提前致谢

好的,

我终于找到了。正是这个特定的行导致了问题,并且必须对内容类型执行某些操作:

contentType = @"application/x-www-form-urlencoded; charset=utf-8";

删除它后,我能够正确地将我的字符串发送到服务器。

我认为服务器抱怨它不知道如何使用内容类型"mimeType"生成响应。

您的接受标头应该是"text/html"或您在响应中期望的任何内容类型,而不是"mimeType"。


更新

再次阅读本文后,我注意到您将 contentType 设置为 @"text/html" ,然后设置为 @"application/x-www-form-urlencoded; charset=utf-8" 。你需要哪个?从描述中,您想发送text/html,但这不是您发送的内容。将contentType设置为 @"application/x-www-form-urlencoded; charset=utf-8" 时,text/html将丢失。

最新更新