【问题标题】:How to set content-type when using initWithContentsOfUrl使用 initWithContentsOfUrl 时如何设置内容类型
【发布时间】:2010-11-22 08:51:15
【问题描述】:

基本上我想设置

Content-Type: application/json;

为了调用 dot net web 服务并让它返回 json 到 iphone 应用程序。

目前有

NSString * jsonres = [[NSString alloc] initWithContentsOfURL:url];

我需要什么来发出阻塞请求?

【问题讨论】:

    标签: iphone objective-c content-type


    【解决方案1】:

    您需要使用 NSURLMutableRequest,在这里您可以为内容类型和排序添加标头,这是参考,http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableURLRequest,一旦您设置了您的请求,您就可以使用此方法添加值 - (void)addValue :(NSString *)HTTPHeaderField 的值:(NSString *) 类似的字段

    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    

    【讨论】:

    • 是的,我认为可以做到。感谢您的快速回复!
    • 虽然它不是阻塞式请求,而是使用委托和回调 - 这将涉及一些重新架构!
    • 对于块状风格你只需要做一个同步调用(忘了提这个抱歉)你可以使用名为 + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returnedResponse:(NSURLResponse **) 的 NSURLConnections 方法响应错误:(NSError **)错误,这是一个链接developer.apple.com/iphone/library/documentation/Cocoa/…
    • 谢谢。我自己想通了,然后回到这里更换我的 cmets :-) 你 5 小时前到达那里!
    • 请不要在主线程中使用 sendSynchronousRequest。这会导致应用表现不佳。
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 2018-11-29
    • 2020-06-29
    • 2019-09-22
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    相关资源
    最近更新 更多