Мой пользователь вводит адрес получателя (почтовый адрес, а не адрес электронной почты). Мне нужно проверить это с USPS, чтобы я знал, что это на самом деле адрес.
Я сейчас копаюсь в их API и думаю, что понимаю, но я не совсем уверен, как это сделать с целью-c.
Так что почти все работает так:
- Мне нужно создать запрос XML, который содержит имя получателя, адрес и почтовый индекс.
- Я должен опубликовать это на их сервере
- Они отвечают XML-ответом
Вот пример того, как выглядит один из их построенных XML-запросов:
http://SERVERNAME/ShippingAPITest.dll?API=Verify&XML=<AddressValidateRequest% 20USERID="xxxxxxx"><Address ID="0"><Address1></Address1>
<Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State> <Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>
Немного искажен, но сломан:
http://SERVERNAME/ShippingAPITest.dll?API=Verify&XML=
<AddressValidateRequest% 20USERID="xxxxxxx">
<Address ID="0">
<Address1></Address1>
<Address2>6406 Ivy Lane</Address2>
<City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>
Моя первая идея кажется очевидной, но, возможно, есть лучший способ сделать это. Поскольку XML-лента короткая, я должен начать конструирование, просто выполнив что-то вроде:
NSString * request = [NSString stringWithFormat: @ "......"]
Где он заполняется и форматируется в соответствии с указаниями выше.
Второй вопрос: как правильно отправить это на сервер?
Я просто создаю запрос NSURL и с URL-адресом в качестве созданной строки XML?
Вот что у меня есть, но я продолжаю понимать, что URL был создан неправильно:
- (void)verifyAddress:(Recipient*)_recipient {
NSURL *_url = [NSURL URLWithString:@"http://testing.shippingapis.com/ShippingAPITest.dll?API=Verify&XML=<AddressValidateRequest%20USERID=\"********\"><Address ID=\"0\"><Address1></Address1><Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>"];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:_url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [NSMutableData data];
NSString* newStr = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"the response '%@'", newStr);
} else {
// Inform the user that the connection failed.
NSLog(@"error");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString* newStr = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"the response '%@'", newStr);
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
}
Я получаю следующую ошибку:
Connection failed! Error - bad URL (null)
Мой единственный вопрос сейчас, все ли я в порядке, что касается NSURLConnection? Я могу поиграть с URL, я просто хочу убедиться, что моя реализация в порядке, поэтому я не бегаю кругами. : P