When I NSLog HTTP requests response string, it appears as "ãÃÂïãÃâ¬ÃÂãÃÂÃâãÃÂ" and something different appears on UILabel but not the same as I expect in Japanese/Chinese format. I am using ASIHTTPRequest and as mentioned here I have set response encoding to NSUTF8StringEncoding(server uses UTF-8 same) but it didn't help. Could someone please tell me how to support unicode character in my App? Thanks.
- (void)getData
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithCapacity:3];
[data setObject:self.username forKey:#"username"];
[data setObject:self.password forKey:#"password"];
NSString *dataJSON = [parser stringWithFragment:data error:nil];
[request appendPostData:[dataJSON dataUsingEncoding:NSUTF8StringEncoding]];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestSuccess:)];
[request setDidFailSelector:#selector(requestFailed:)];
[self.queue addOperation: request];
[self.queue go];
}
- (void)requestSuccess:(ASIHTTPRequest *)request
{
NSLog(#"success: %#", [request responseString]);
}
I managed to fix this. Following is the change!
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding]; -- > Wrong!!!
request.defaultResponseEncoding = NSUTF8StringEncoding; --> Correct!
Related
I got the following Postman request which works fine (Screenshot http://postimg.org/image/s7zm3qhvh/). But when i try the same in iOS it will not work. Maybe someone can give me some information why.
My Objective-c Code:
UIImage *yourImage= [UIImage imageNamed:#"login-main-bg.png"];
NSString *imageString = [UIImagePNGRepresentation(yourImage) base64Encoding];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
imageString, #"image",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(#"%#",[error localizedDescription]);
}
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://server.website.net/api/collaboration/ImageTest"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
//print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
I hope someone can help me! Thank you!
You're posting a json representation of a base64 encoded string of your image. The postman request is doing a raw binary post with multipart form boundaries.
You want something more like what is shown here https://stackoverflow.com/a/23517227/96683
Hi im trying to make a POST request
my code:
NSURL *url = [NSURL URLWithString:urlString];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setCompletionBlock:^{
NSString *result = [request responseString];
NSDictionary *dict = [result JSON];
NSLog(#"dict -%#",dict);
}];
[request setFailedBlock:^{
NSLog(#"error %#",[request error]);
}];
[request startAsynchronous];
when I run my code it returns a (null) value. My urlString is correct and the request didn't give me error also. I've tried it on web and returns a {"status":"success"} (it will return a dictionary with status successful or failed).
Use Like this. Hope this will help.
-(void)exe method
{
NSString *strURL=#"---your URL----";
NSURL *url=[NSURL URLWithString:strURL];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error;
if(!error)
{
NSString *receivedString = [request responseString];
NSDictionary *dic = [receivedString JSONValue];
NSLog(#"output %#",dic);
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Try with this code -
NSURL *url = [NSURL URLWithString:urlString];
__unsafe_unretained ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
__block id jsonData;
[request setTimeOutSeconds:300];
[request setCompletionBlock:^(){
NSError *error = nil;
NSString *responseString = (request.responseString.length)?request.responseString:#"";
NSLog(#"%#",responseString);
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if(error)
completionBlock(nil, error, task);
else
completionBlock(jsonData, error, task);
}];
[request setFailedBlock:^{
completionBlock(nil, request.error, task);
}];
[request startAsynchronous];
Might be it will helpfull for you.
Did you set your headers in the script that returns JSON correctly? Assuming you're using PHP:
header('Content-Type: application/json');
The default MIME-type is "text/plain", instead of "application/json". If you dont set the MIME-type correctly you're basicly trying to parse the whole document.
So instead of:
{"status":"success"}
You are most likely trying to parse:
<html>
<head></head>
<body>{"status":"success"}</body>
</html>
-(void)exe method
{
NSString *strURL=#"---your URL----";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
I am stuck with an issue in simple request response in iOS, I am getting blank response in request a url with one post parameter, where the url as it is perfectly working in android and webbrowser
Friends in detail, I have to call
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
it is working before, but from last few days it is not working, if I check NSError it is showing me The network connection was lost.
and one more thing noticeable here is same server code is on different url and it is working fine, and that url you can test as below
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
Here is the dropbox link for testing ios source code and also the folder contains Web services test.htm file to test that same url with same post parameter working in browser but not in ios device.
Testing code:
https://dl.dropboxusercontent.com/s/lqrl5b95j2s54mm/Testing.zip?token_hash=AAFgoNfUpQ4FkeswnPdGiMVzdMtSM6js9KySJm_OH6lZXQ&dl=1
thank you
So I could not get the form per se to work but was able to recraft it to work. Note a few things:
you should convert to ARC!
you need a strong reference to the connection so you can release it later on (and not in a delegate method!)
you need the delegate connectionSucceeded method (to record response whatever!)
CODE:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *requesturl = lblURL.text;
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"content-type"];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *str = [NSString stringWithFormat:#"key=%#", [self URLencodedString:#"Abcd1234"]];
NSLog(#"BODY: %#", str);
NSData *body = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%u", [body length]] forHTTPHeaderField:#"Content-Length"];
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
self.activeDownload = [NSMutableData data];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
assert([response isKindOfClass:[NSHTTPURLResponse class]]);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"GOT %d", [httpResponse statusCode]);
}
- (NSString *)URLencodedString:(NSString *)s
{
CFStringRef str = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)s, NULL, (CFStringRef)#"!*'();:#&;=+$,/?%#[]", kCFStringEncodingUTF8);
NSString *newString = [(NSString *)str stringByReplacingOccurrencesOfString:#" " withString:#"+"];
if(str) CFRelease(str);
return newString;
}
EDIT: Modified Code that still didn't work:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *boundary = #"1010101010"; // DFH no need for the leading '--'
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableDictionary *postVariables = [[NSMutableDictionary alloc] init];
[postVariables setValue:#"Abcd1234" forKey:#"key"];
NSString *requesturl = lblURL.text;
NSMutableString *myStr = [[NSMutableString alloc] init];
NSString *str;
// DFH - strategy is to have each line append its own terminating newline/return
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH initial boundary
[myStr appendString:str];
NSArray *formKeys = [postVariables allKeys];
for (int i = 0; i < [formKeys count]; i++) {
str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n%#\r\n",[formKeys objectAtIndex:i],[postVariables valueForKey:[formKeys objectAtIndex:i]]];
[myStr appendString:str];
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH mid or terminating boundary
[myStr appendString:str];
}
NSLog(#"BODY: %#", myStr);
NSData *body = [myStr dataUsingEncoding:NSUTF8StringEncoding];
requesturl = [self encodeStringForURL:requesturl];
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
self.activeDownload = [NSMutableData data];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"]; // DFH you add addValue, I always use setValue
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
NSLog(#"ContentType \"%#\"", contentType);
if(body)
{
[request setHTTPBody:body];
}
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
I have used ASIHTTP Library and my problem is solved
I am trying to verify a non-renewable subscription with Apple's sandbox server but keep getting back verify response: { "status":21002 } which means the request is malformed. Here is the relevant code I am using:
NSString *receiptString = [[NSString alloc] initWithData:transactionReceipt
encoding:NSUTF8StringEncoding];
NSString *encodedString = [receiptString base64Encoding];
NSString *jsonString = [NSString stringWithFormat:#"{ 'receipt-data' : '%#' }", encodedString];
NSURL *verificationURL = [NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:verificationURL];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(#"verify response: %#", responseString);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"verify error: %#", [error description]);
}];
[request startAsynchronous];
Apparently the problem is the way I am sending the data to Apple through the ASIHTTPRequest library. Any insight on this appreciated. Thanks in advance!
Try to use another code. Example,
IAP_Validation
I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.