http请求带json格式不能请求数据
在做请求http时,后面的参数格式为json字符串,请求后,服务端无响应,且无数据返回,不报异常。当换成其它带参http时,可以正常返回数据。开始以为是末转义参数中的大括号,后来把大括号替换为中括号就正常了,不知为何要这样处理?
代码如下:
#define REQUEST_URL @"http://127.0.0.1:9091/?param={%22className%22:%22AppServiceImpl%22,%22methodName%22:%22doSelect%22,%22parameter%22:%22test%22}"
- (IBAction)requestHttpBtn:(id)sender {
NSString *jsonStr = [REQUEST_URL stringByReplacingOccurrencesOfString:@"{" withString:@"]"];
[jsonStr stringByReplacingOccurrencesOfString:@"}" withString:@"]"];
NSURL *url = [NSURL URLWithString:jsonStr];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:url];
[request setHTTPMethod:@"POST"];
// [request addValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
// [request setValue:@"test" forHTTPHeaderField:@"User-Agent"];
NSHTTPURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(@"data : %@",[data description]);
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//showTxt.text = result;
NSLog(@"Result : %@",result);
}今天完善http通过json格式参数通信例子,昨天的问题已解决,其实不需要替换大括号的,对请求的url进行转码就可以了。如下代码:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
//想通过对象直接转为json,暂时还没解决方案
// LoginResquest *loginResquest = [[LoginResquest alloc] init];
// [loginResquest setClassName:@"AppServiceImpl"];
// [loginResquest setMethodName:@"methodName"];
// [loginResquest setPassword:password];
// [loginResquest setUserName:userName];
// [dictionary setValue:loginResquest forKey:@"LoginResquest"];
[dictionary setValue:@"AppServiceImpl" forKey:@"className"];
[dictionary setValue:@"doSave" forKey:@"methodName"];
NSMutableDictionary *loginDic = [[NSMutableDictionary alloc] init];
[loginDic setValue:password forKey:@"password"];
[loginDic setValue:userName forKey:@"userName"];;
[dictionary setValue:loginDic forKey:@"LoginRequest"];
NSMutableString *urlStr = [[NSMutableString alloc] initWithString:REQUEST_URL];
NSString *aStr = [dictionary JSONRepresentation];
//以下为url进行转码
aStr = [aStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//NSASCIIStringEncoding
[urlStr appendString:aStr];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:url];
[request setHTTPMethod:@"POST"];
NSHTTPURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Result : %@",result); ss
相关推荐
86193952 2020-10-27
87403867 2020-09-24
88550291 2020-08-21
88407710 2020-08-17
xvzhengyang 2020-07-30
knightwatch 2020-07-19
knightwatch 2020-07-04
hygbuaa 2020-06-26
sicceer 2020-06-21
88407013 2020-06-16
86447405 2020-06-16
zkwgpp 2020-06-14
DumbbellYang 2020-06-11
标题无所谓 2020-06-10
hygbuaa 2020-06-10
zkwgpp 2020-06-02
zhaolisha 2020-05-31