我想进行一个包含URL参数和JSON正文的POST调用:
URL http://example.com/register?apikey=mykey
JSON { "field" : "value"}
如何在AFNNetworking的同时使用两个不同的序列化程序?这是我的代码,缺少URL参数:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:@"http://example.com/register" parameters:json success:^(AFHTTPRequestOperation *operation, id responseObject) {
答案 0 :(得分:3)
我制作了一个帖子方法
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == 2) {
Uri selectedImageUri = data.getData();
FilePath=selectedImageUri.toString();
FilePath=selectedImageUri.toString();
// uploadFile();
if (resultCode == RESULT_OK){
File imagefile = new File(FilePath);
Log.e("FilePath",FilePath);
String byteArrayStr = "";
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("FIle Not found" +FilePath, "");
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 75, baos);
byte[] data1 = baos.toByteArray();
totalSize = data1.length;
String strBase64 = Base64.encodeToString(data1,
0).toString();
try {
SoapObject request = new SoapObject(NAMESPACE,
"InsertFile");
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
MarshalBase64 marshal = new MarshalBase64();
marshal.register(envelope);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
request.addProperty("FromUsername",
LoginActivity.username.toString());
request.addProperty("ToUsername",name[1]);
request.addProperty("filetype", ".png");
request.addProperty("f", data1);
HttpTransportSE AndroidHttpTransportSE = new
HttpTransportSE(URL);
try {
AndroidHttpTransportSE.call(NAMESPACE +
"InsertFile",envelope);
// http://scm.org/UserDetails
} catch (XmlPullParserException e) {
e.printStackTrace();
}
SoapPrimitive result = (SoapPrimitive)
envelope.getResponse();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"No file
}}}
**例如我们致电服务**
/**
* Services gateway
* Method get response from server
* @parameter -> object: request josn object ,apiName: api endpoint
* @returm -> void
* @compilationHandler -> success: status of api, response: respose from server, error: error handling
*/
+ (void)getDataWithObject:(NSDictionary *)object onAPI:(NSString *)apiName withController:(UIViewController*)controller
:(void(^)(BOOL success,id response,NSError *error))compilationHandler {
controller = controller;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request type to json
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// post request to server
[manager POST:apiName parameters:object success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0
error:&error];
//NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
////
// check the status of API
NSDictionary *dict = responseObject;
NSString *statusOfApi = [[NSString alloc]initWithFormat:@"%@"
,[dict objectForKey:@"OK"]];
// IF Status is OK -> 1 so complete the handler
if ([statusOfApi isEqualToString:@"1"] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
compilationHandler(TRUE,responseObject,nil);
} else {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *errorMessages = [responseObject objectForKey:@"messages"];
NSString *message = [errorMessages objectAtIndex:0];
[Utilities showAlertViewWithTitle:apiName message:message];
compilationHandler(FALSE,responseObject,nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *message = [NSString stringWithFormat:@"%@",[error localizedDescription]];
NSLog(@"Message is %@", message);
NSString *errorMessage = [NSString stringWithFormat:@"%@",[error localizedDescription]];
if (!([message rangeOfString:@"The request timed out."].location == NSNotFound)) {
[Utilities showAlertViewWithTitle:apiName message:errorMessage];
}
compilationHandler(FALSE,errorMessage,nil);
}];
// For internet reachibility check if changes its state
[self checkInternetReachibility:manager];
}
答案 1 :(得分:0)
我相信没有自动的方法。但是,有一种简单的方法可以手动实现它:
- (NSMutableURLRequest *)someRequestWithBaseURL:(NSString *)baseUrl
method:(NSString *)method
path:(NSString *)path
uriParameters:(NSDictionary *)uriParameters
bodyParameters:(NSDictionary *)bodyParameters
NSURL *url = [NSURL URLWithString:path relativeToURL:[NSURL URLWithString:baseUrl]];
AFHTTPRequestSerializer *httpRequestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:0]
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:bodyParameters];
if ([httpRequestSerializer.HTTPMethodsEncodingParametersInURI containsObject:method]) {
[parameters addEntriesFromDictionary:uriParameters];
} else {
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
// For urlEncodedString, check http://stackoverflow.com/a/718480/856549
urlComponents.percentEncodedQuery = [uriParameters urlEncodedString];
url = [urlComponents URL];
}
NSError *error;
NSURLRequest *request = [httpRequestSerializer requestWithMethod:method
URLString:[url absoluteString]
parameters:parameters
error:&error];