使用IOS进行身份验证的Restful API调用

前端之家收集整理的这篇文章主要介绍了使用IOS进行身份验证的Restful API调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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);

请告诉我我做错了什么并提供任何解决方案.

谢谢!

解决方法

您可以通过这种方式构建URL字符串,它应该可以工作: –
NSString *str1 = [NSString stringWithFormat:@"http://%@:%@@www.example.com/api",password];

我不相信使用HTTP头字段

原文链接:/iOS/328192.html

猜你在找的iOS相关文章