iPhone上的错误网址,当我在浏览器中输入它时,它可以工作

时间:2013-01-10 15:38:40

标签: ios json url didfailwitherror

我正在制作一个jsonstring。当我执行它时,它在我的浏览器中执行时有效。我这样做是通过记录确切的URL并将其复制到浏览器中。比我得到我想要的HTTP Get,但在iPhone中我只得到一个糟糕的登录。

- (IBAction)getDown:(id)sender { //perform get request
    NSLog(@"beginnen met versturen");

    //NSString * _barCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];

    //build up the request that is to be sent to the server
    //NSString*jsonString = [[NSString alloc] initWithFormat:@"{\"barcode\":\"%@\"}", _barCode];


    NSString*jsonString = [[NSString alloc] initWithFormat:@"{\"barcode\":\"123456\"}"];

    NSString *str = [NSString stringWithFormat: @"http://server.nl/scan.php?data=%@",jsonString];
    NSLog(@"%@", str);
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL    URLWithString:str]];
    NSLog(@"url: %@", request);

    [request setHTTPMethod:@"GET"];
   // [request addValue:@"getValues" forHTTPHeaderField:@"METHOD"]; //selects what task the server will perform
    NSLog(@"met value: %@", request);

    //initialize an NSURLConnection  with the request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data

    receivedData = data;
    /* NOTE: if you are working with large data , it may be better to set recievedData as NSMutableData
     and use  [receivedData append:Data] here, in this event you should also set recievedData to nil
     when you are done working with it or any new data received could end up just appending to the
     last message received*/
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails

    NSLog(@"Connection failed with error: %@",error.localizedDescription);
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{

    /*This message is sent when there is an authentication challenge ,our server does not have this requirement so we do not need to handle that here*/
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSLog(@"Request Complete,recieved %d bytes of data",receivedData.length);

    //[self.delegate requestReturnedData:receivedData];//send the data to the delegate
    NSData *data = receivedData;
    NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
    NSLog(@"%@",dictionary.JSONString ); ; // set the textview to the raw string value of the data recieved

    NSString *value1 = [dictionary objectForKey:@"barcode"];
    NSLog(@"%@", value1);
    NSString *value2 = [dictionary objectForKey:@"product"];
    NSLog(@"%@",dictionary);
    NSLog(@"%@", value2);

}

这是日志:

2013-01-10 16:31:46.550 Scanner[14875:907] http://server.nl/scan.php?data={"barcode":"123456"}
2013-01-10 16:31:46.551 Scanner[14875:907] url: <NSMutableURLRequest (null)>
2013-01-10 16:31:46.553 Scanner[14875:907] met value: <NSMutableURLRequest (null)>
**2013-01-10 16:31:46.556 Scanner[14875:907] Connection failed with error: bad URL**

当我从字符串中删除完整的json时,我得到的不是坏网址。所以可能存在问题。谁知道我做错了什么?

2 个答案:

答案 0 :(得分:3)

在执行URL请求之前,您需要对其进行编码。 最好和最优雅的解决方案是在NSString上添加一个类别,例如:

- (NSString*)URLEncode {
    // Should not be encoded:-_.
    return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(";/?:@&=+$,!*'()<>#%\"{}|\\^[]`~"), kCFStringEncodingUTF8) autorelease];
//
}

当你提出要求时:

NSString *str = [NSString stringWithFormat: @"http://server.nl/scan.php?data=%@",jsonString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL    URLWithString:[str URLEncode]];

如果您不想使用其他文件(甚至认为是推荐的),请将此方法添加到您的班级:

- (NSString*)URLEncode:(NSString )yourURL {
 // Should not be encoded:-_. 
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(";/?:@&=+$,!'()<>#%\"{}|\\^[]`~"), kCFStringEncodingUTF8) autorelease]; 
} 

并使用

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[self URLEncode:str]]; 

答案 1 :(得分:1)

我现在没有太多信息,我道歉,我有点急,只是看到了你的问题。但是我看到了你的问题,我记得我正在开发一个基本上是基于HTML的iphone遥控器的项目,当用户点击遥控器的一些按钮时,它会跟随打开相同页面的网址,但是服务器端代码,指示服务器暂停,播放,停止等...我记得iPhone有一个错误导致它无法解析我的所有URL,即使它们格式正确并且工作正常在桌面客户端上。这就是为什么我切换到POST请求(用户点击而不是激活javascript函数,设置隐藏的表单变量,然后提交表单而不是直接导航到长URL)。无论如何,我知道这可能不会直接适用于你,但重点是我确实在iPhone的URL解析中发现了一个错误,所以它可能不是你的错。我会查找稍后可以找到的任何新信息。祝你好运。