我正在开发一个应用程序,使用prestashop API 进行restful API调用。 我在IOS上是新手,我在Android上编写了相同的方法如下:
InputStream is = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
/* adding credentials as it is RESTful call */
String username = "xyz";
String password = "";
client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),new UsernamePasswordCredentials(username, password));
// HTTP get request
HttpGet get = new HttpGet("http://www.example.com/api/");
HttpResponse responseGet;
responseGet = client.execute(get);
is = responseGet.getEntity().getContent();
} catch (ClientProtocolException e) {
Log.e("HTTP Request","Client Protocol exception" );
} catch (IOException e) {
Log.e("HTTP Request","IO exception" );
}
对于Android来说,它运行得非常完美。对于IOS,我使用了这段代码,但是我无法从服务器获取数据。
NSString *userName = @"XYZ";
NSString *password = @"";
//setting the string of the url taking from appliance IP.
NSString *urlString = @"http://www.example.com/api/";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];
NSString *str1 = [NSString stringWithFormat:@"%@:%@",userName,password];
NSLog(@" str1 %@", str1);
[request addValue:[NSString stringWithFormat:@"Basic %@",str1] forHTTPHeaderField:@"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"str: %@", str);
请告诉我我做错了什么,并提供任何解决方案。
谢谢!