我正在开发一个使用 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);
请告诉我我做错了什么并提供任何解决方案。
谢谢!