#ios #objective-c #xml #cocoa-touch #nsurlrequest
#iOS #objective-c #xml #cocoa-touch #nsurlrequest
Вопрос:
Я хочу отправить XML-файл в http://api.online-convert.com/queue-insert
Я использую такой код:
NSString *urlString = [NSString stringWithFormat:@"http://api.online-convert.com/queue-insert"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:@"text/xml"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"<queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<apiKey>32423sda..2134</apiKey>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<targetType>audio</targetType>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<targetMethod>convert-to-flac</targetMethod>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<testMode>true</testMode>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"</queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:amp;urlResponse error:amp;error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 amp;amp; [urlResponse statusCode] < 300) {
NSLog(@"Response: %@", result);
}
Но я всегда получаю сообщение об ошибке:
<queue-answer>
<status>
<code>8</code>
<message>The XML file is empty</message>
</status>
</queue-answer>
В чем моя ошибка? Пожалуйста, помогите..
Комментарии:
1. Ознакомьтесь с AFNetworking. В нем есть классы, которые делают запросы XML и JSON тривиальными.
2. У вас есть ответ на этот вопрос?
3. Вы нашли ответ?
4. привет, ты решил это?
Ответ №1:
Я отправляю XML-файл следующим образом:
NSString *message = [[NSString alloc] initWithFormat:@"<?xml version="1.0" ?>n<parameters></parameters>"];
url = [NSURL URLWithString:@"https://site.ru/request"];
request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d",[message length]];
[request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
LOG([NSString stringWithFormat:@"Post message: %@"], message);
[message release];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
Комментарии:
1. Вы изменили тип контента и установили его длину?
Ответ №2:
Вы, вероятно, не знаете, что делаете. В строке:
[postBody appendData:[[NSString stringWithFormat:@"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
Предполагается, что вы отправляете URL-адрес на сервер, где находится ваш исходный файл (файл, который вы хотите преобразовать). Ссылка в вашем коде ведет к несуществующему файлу.
Комментарии:
1. Это не имеет значения. Он пишет
The XML file is empty
, поэтому, если я удалю или заменю этот параметр, это ничего не изменит
Ответ №3:
Этот фрагмент кода работает для меня:
- (IBAction)startSOAP:(id)sender
{
NSLog(@"n{AppDelegate} startSOAP start");
// create the request
NSError **myError;
NSHTTPURLResponse **serverResponse;
NSData *serverData;
NSDictionary *headerFieldsDict = [NSDictionary
dictionaryWithObjectsAndKeys:@"Apple iPhone",@"User- Agent",
@"text/xml; charset=utf-8", @"Content-Type",
@"soapAction",@"SOAP_ACTION",nil];
@try {
// 1) The Request String.
// Note: smsXMLString contains the entire SMS SOAP envelope, without the <? XML declaration command >.
NSString *smsXMLPath = [[NSBundle mainBundle] pathForResource:@"sms" ofType:@"xml"];
self.smsXMLString = [NSString stringWithContentsOfFile:smsXMLPath encoding:NSUTF8StringEncoding error:myError];
// -----------------------
// 2) Create the request.
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theServerURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
// -----------------------
// 2a) Modify the Request from default 'GET' to 'POST':
[theRequest setHTTPMethod:@"POST"];
// 2b) Modify the Headers:
[theRequest setAllHTTPHeaderFields:headerFieldsDict];
// 2c) Sent the Contents of the Body to the SOAP/XML data:
[theRequest setHTTPBody:[self.smsXMLString dataUsingEncoding:NSUTF8StringEncoding]];
// -----------------------
// 3) Get Synchronous Data:
serverData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:serverResponse
error:myError];
// -----------------------
// 4) Convert Synchronous Data into Human-Readable String (Unicode 8) format:
NSString *serverDataString = [[[NSString alloc] initWithData:serverData encoding:NSUTF8StringEncoding] retain];
[[soapResponse layoutManager]replaceTextStorage:[[NSTextStorage alloc] initWithString:serverDataString]];
[serverDataString release];
}
@catch (id e) {
NSLog(@"n**** {startSOAP} EXCEPTION: %@ ****n",e);
self.statusLine.stringValue = [NSString stringWithFormat:@"*** Exception flagged: %@ ***",e];
}
@finally {
NSLog(@"n{startSoap} end.");
}
}