我尝试使用 API 调用 TextGetRankedNamedEntities http://www.alchemyapi.com/api/entity/textc.html#rtext
这是我的相关代码:
NSString *data = @"Data I want analyzed";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"result.txt"];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
//I have verified the data is in the file
NSString *queryString = [NSString stringWithFormat:@"http://access.alchemyapi.com/calls/text/TextGetRankedNamedEntities?apikey=MY_API_KEY&showSourceText=1"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
requestWithURL:[
NSURL URLWithString: queryString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
//Set request method to post
[theRequest setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"&text=%@", appFile];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[theRequest setHTTPBody:postData];
我对此请求的结果是:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<status>OK</status>
<usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</usage>
<url></url>
<language>english</language>
<text>/var/mobile/Containers/Data/Application/6C00A4F8-4DEE-44F2-9DBF-7568CEF72054/Documents/result.txt</text>
<entities>
</entities>
</results>
似乎正在发送的数据是文件路径,而不是文件的实际内容。
编辑:已解决,将问题留给在iOS中使用HTTTP请求的可能反馈和最佳实践,因为我对两者都很陌生。
更改:
NSString *post = [NSString stringWithFormat:@"&text=%@", appFile];
自:
NSString *post = [NSString stringWithFormat:@"&text=%@", data];
在发布问题之前我没有想到要尝试这样做,因为我以前曾尝试过这样做,但那时我使用 GET 方法而不是 POST 方法发送请求。