如何在iOS中发送和接收web服务请求和响应?
我有一个基于ApacheCXF的web服务和Android应用程序,它使用下面的代码向它发送请求 现在,我想编写一个简单的iOS应用程序,它将相同的请求发送到相同的web服务,但来自iOS设备 学习如何使用英语的好起点是什么如何在iOS中发送和接收web服务请求和响应?,ios,objective-c,json,web-services,Ios,Objective C,Json,Web Services,我有一个基于ApacheCXF的web服务和Android应用程序,它使用下面的代码向它发送请求 现在,我想编写一个简单的iOS应用程序,它将相同的请求发送到相同的web服务,但来自iOS设备 学习如何使用英语的好起点是什么 JSON 发送web服务请求和 从服务器接收响应 在目标C中 SaveLocationAsyncTask.java public class SaveLocationAsyncTask extends AbstractAsyncTask<SaveLoc
public class SaveLocationAsyncTask extends
AbstractAsyncTask<SaveLocationRequest, SaveLocationResponse> implements
ISaveLocationAsyncTask {
private static final String SERVICE_NAME = "SaveLocation";
public SaveLocationAsyncTask(final IWebServiceTaskHelper aHelper,
final ILogger aLogger, final IServerUrlStorage aServerUrlStorage) {
super(aHelper, SaveLocationResponse.class, aLogger,
new CbResponseParser<SaveLocationResponse>(), aServerUrlStorage,
SERVICE_NAME);
}
}
import android.os.AsyncTask;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.ExecutionException;
public class AbstractAsyncTask<Request, Response> extends
AsyncTask<String, String, Response> implements
IRequestSender<Request, Response> {
private static final String REQUEST_AS_JSON_PARAMETER_NAME = "request";
private IWebServiceTaskHelper helper;
private Class<Response> responseClass;
private ILogger logger = null;
private IResponseParser<Response> responseParser = null;
private IServerUrlStorage serverUrlStorage;
private String serviceName;
public AbstractAsyncTask(final IWebServiceTaskHelper aHelper,
final Class<Response> aResponseClass, final ILogger aLogger,
final IResponseParser<Response> aResponseParser,
final IServerUrlStorage aServerUrlStorage, final String aServiceName) {
helper = aHelper;
responseClass = aResponseClass;
logger = aLogger;
responseParser = aResponseParser;
serverUrlStorage = aServerUrlStorage;
serviceName = aServiceName;
}
private String convertToJson(final Object aRequest) {
final ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(aRequest);
} catch (final JsonProcessingException exception) {
logger.error(exception);
}
return json;
}
@Override
protected Response doInBackground(final String... aParams) {
logger.debug("doInBackground: " + aParams);
return new ResponseProcessor<Response>(logger, helper, responseParser,
responseClass).processResponse(aParams);
}
@Override
public Response sendRequest(final Request aRequest)
throws InterruptedException, ExecutionException {
final String json = convertToJson(aRequest);
final String url = serverUrlStorage.getServerUrl() + serviceName;
helper.addNameValuePair(REQUEST_AS_JSON_PARAMETER_NAME, json);
execute(url);
return get();
}
}
beans.xml的片段:
web服务TestMessage
的URL似乎是http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-服务器/mobilecsdemo/TestMessage
在iOS端发送请求的代码:
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"message"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-server/mobilecsdemo/TestMessage"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", retStr);
http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-服务器/mobilecsdemo?_wadl
显示以下内容:
<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-server/mobilecsdemo/">
<resource path="/TestMessage">
<method name="POST">
<request>
<representation mediaType="application/x-www-form-urlencoded">
<param name="request" style="query" type="xs:string"/>
</representation>
</request>
<response>
<representation mediaType="text/plain">
<param name="result" style="plain" type="xs:string"/>
</representation>
</response>
</method>
</resource>
</resources>
</application>
这将为你服务。根据需要调整词典
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
此外,NSURLConnection还有一种异步方法:
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *res3, NSData *data, NSError *connectionError) {
NSString *retStr = [[NSString alloc] initWithData:data];
}
正如Rohan Panchal在评论中提到的,它是一个非常好的第三方库,很好地包装了这些方法。我个人更喜欢裸骨连接方式。这将很好地为您服务。还有其他一些库,例如AFNEtworking,它将NSURLConnection类包装在一个易于使用的界面中,但是学习barebones networking库的工作原理是必不可少的,而且实际上对您来说可能会容易得多。@DJ_electr0谢谢,发送请求似乎可行,但存在一些问题-请参阅我的更新1。
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"message"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-server/mobilecsdemo/TestMessage"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", retStr);
<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<grammars/>
<resources base="http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-server/mobilecsdemo/">
<resource path="/TestMessage">
<method name="POST">
<request>
<representation mediaType="application/x-www-form-urlencoded">
<param name="request" style="query" type="xs:string"/>
</representation>
</request>
<response>
<representation mediaType="text/plain">
<param name="result" style="plain" type="xs:string"/>
</representation>
</response>
</method>
</resource>
</resources>
</application>
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"message"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://AAA.BBB.CCC.DDD:8080/mobilecsdemo-server/mobilecsdemo/TestMessage"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
NSString* body = @"request={\"message\":\"message content\"}";
NSData *someData = [body dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPBody:someData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(@"jsonData: %@", jsonData);
NSLog(@"Response: %@", retStr);
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *res3, NSData *data, NSError *connectionError) {
NSString *retStr = [[NSString alloc] initWithData:data];
}