我试图最终得到NSMutableURLRequest一个有效的HTTPBody,但我似乎无法将我的字符串数据(来自a UITextField)变成可用NSData对象.
我已经看到这种方法走另一条路:
NSString(data data: NSData!, encoding encoding: UInt)
但我似乎无法为我的用例找到任何文档.如果有必要,我愿意将字符串放入其他类型,但是NSData使用Swift 的初始化选项似乎都不是我想要的.
如何使用NSLog打印NSMutableURLRequest?
我正在发布一个小图片,所以我希望超时间隔很短.如果图像在几秒钟内没有发送,它可能永远不会发送.由于某种未知的原因NSURLConnection,无论我设置多短,我都永远不会失败timeoutInterval.
// Create the URL request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
                                 initWithURL:[NSURL URLWithString:@"http://www.tumblr.com/api/write"]
                                 cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:0.00000001];
/* Populate the request, this part works fine */
[NSURLConnection connectionWithRequest:request delegate:self];
我有一个断点,- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error但它永远不会被触发.我的图像继续张贴得很好,尽管很小,它们仍然出现在Tumblr上timeoutInterval.
我想问一下是否有人试过打印出NSMutableURLRequest*请求的值;
这是我的场景,我已经形成了我的XML,并尝试使用Firefox Poster插件发送它,我成功播放有效和无效的内容,所以它的时间进入iOS,不幸的是,它似乎没有正常工作,我总是得到错误请求(400)的响应,我怀疑是由错误的xml内容引起的; 所以我在发送请求之前正在考虑我要检查它是否在正确的表单上.
所以它归结为"如何打印出来(nslog等等)*请求的内容"
示例代码如下:
    NSURL *URL = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx/ps"];
    NSMutableURLRequest *request = [NSMutableURLRequest                                         requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [self.xmlLogin length]];
    //NSString *params = [[NSString alloc] initWithFormat:@"%@",[self xmlLogin]];
    [request addValue:@"application/xxx.ven.xml" forHTTPHeaderField:@"Content-Type"];
    [request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
    [request setValue:@"windows-1251" forHTTPHeaderField:@"Accept-Charset"];
    [request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    [request setHTTPBody:[[self xmlLogin] dataUsingEncoding:NSUTF8StringEncoding]];
这段代码片段
NSLog(@"Request %@\n",request);
结果
<NSMutableURLRequest http://xxx.xxx.xxx.xxx/ps>
做的事情
NSLog(@"Request %@\n",[request HTTPBody]);
结果
<4c697665 3e383634 30303c2f 54696d65 546f4c69 76653e20 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 203c5365 …我正在创建一个NSMutableRequest:
self.req = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
超时设置为10秒,因为我不希望用户等待太长时间来获得反馈.之后我创建了一个NSURLSessionDataTask:
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:self.req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSHTTPURLResponse * httpResp = (NSHTTPURLResponse *)response;
    if (error) {
        // this is where I get the timeout
    } 
    else if (httpResp.statusCode < 200 || httpResp.statusCode >= 300) {
        // handling error and giving feedback
    } 
    else {
        NSError *serializationError = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&serializationError];
    }
    [task resume];
}
问题是服务器进入Gateway Timeout并且需要花费很多时间.我收到超时错误并向用户提供反馈,但由于超时错误,以下所有API调用都以相同方式失败.阻止它的唯一方法是杀死应用程序并重新开始.在超时错误后,我应该做些什么来终止任务或连接?如果我没有设置超时并且我等到从服务器收到错误代码,则以下所有调用都能正常工作(但是用户会等待很多!).
我试图取消任务:
NSURLSessionDataTask …当我WKWebView使用身份验证cookie 创建新请求并发送请求时,WKWebView正确加载受保护的网页:
let req = NSMutableURLRequest(URL: NSURL(string: urlPath)!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies([myAuthCookie]);
req.allHTTPHeaderFields = headers;
webView.loadRequest(req)
问题是,当用户点击网页中的任何链接时,新请求将WKWebView丢失身份验证cookie并重定向到登录页面.Cookie域和路径已填充且正确.
我知道这里WKWebView提到的功能缺失.
提前感谢任何想法.
我正在构建一个使用单点登录的应用程序,供用户登录.用户输入成功的ID和密码后,Web端会返回我抓取并存储在应用程序中的标题.WKWebView还设置用户成功登录的cookie.这是我想要避免或撤消的.
我看到的不受欢迎的行为是,如果我登录用户,一切顺利,然后我将它们注销并再次重新登录,WKWebView认为用户仍然登录并将他们带到了一个不受欢迎的行为URL.
在iOS 9中,缓解这一点非常简单:
let config = WKWebViewConfiguration()
config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()
let webView = WKWebView(frame: .zero, configuration: config)
但是在iOS 8.4中,确保每次用户进入加载单点登录URL时cookie都是清晰的.
我尝试过循环访问cookie NSHTTPCookieStorage.sharedHTTPCookieStorage()并删除它们的方法.不幸的是,cookie计数为0.
我也尝试删除/Cookies目录NSFileManager.defaultManager().这也行不通.
一件事情,就是那种工作是做以下.虽然这种方法不允许我获取标题,因为登录后需要重定向并且受到干扰(在iOS 9+和8.4中)
req = NSMutableURLRequest(URL: url)
req?.HTTPShouldHandleCookies = false
let webView = WKWebView()
webView.loadRequest(req ?? NSURLRequest(URL: url))
deinit如果这是一个可能的解决方案,我宁愿在我的视图中清除包含我的WKWebView的cookie.
我读了Cocoa和Objective C:Up and Running,-copy它将始终返回一个不可变对象并-mutableCopy始终返回一个可变对象:
重要的是要知道调用
-copy一个可变对象会返回一个不可变的版本.如果要复制可变对象并在新版本中保持可变性,则必须调用-mutableCopy原始对象.但这很有用,因为如果你想"冻结"一个可变对象,你可以调用-copy它.
所以我有这样的事情:
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
NSLog( @"%@", [req className] );               // NSMutableURLRequest
NSLog( @"%@", [[req copy] className] );        // NSMutableURLRequest
NSLog( @"%@", [[req mutableCopy] className] ); // NSMutableURLRequest
根据之前的回答:
你不能依赖复制的结果是可变的!复制一个
NSMutableArray可以返回一个NSMutableArray,因为那是原始类,但复制任意NSArray实例都不会.
这似乎有点孤立NSURLRequest,因为NSArray按预期行事:
NSArray *arr = [[NSMutableArray alloc] init];
NSLog( @"%@", [arr className] );                 // __NSArrayM
NSLog( @"%@", [[arr copy] className] …我正在努力使用https请求Web服务.我收到这样的错误:
An error occured : The certificate for this server is invalid. You might be connecting to a server that is pretending to be “SERVER_ADDRESS” which could put your confidential information at risk.
我没有使用NSUrlConnectionDelegate.这是我的方法:
- (void)sendRequestWithUrl:(NSURL*)url block:(void (^)(NSDictionary *dict, NSError *error)) block{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    NSError* err = nil;
    NSHTTPURLResponse* rsp = nil;
    // Perform the request synchronously on this thread
    NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
    if (rspData && …我想知道设置标头值和向NSMutableURLRequest添加标头值之间的区别是什么.听起来很明显但是,例如,你不能每次都使用addValue吗?设置不存在的标头会引发错误吗?将在请求中已存在的标题添加时会覆盖现有值吗?
例
let request.NSMutableURLRequest(URL: NSURL(string: "someURL")!) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
...