HTTPRequest for forum login - Objective C - objective-c

I am trying to implement this code in Objective C:
Public Shared Function Login(ByVal Username As String, ByVal Password As String) As Boolean
Dim str As String = Func.ConvertToHex(Username)
Http.GetResponse("http://www.website.com/forum/login.php?do=login", String.Concat(New String() { "vb_login_username=", str, "&vb_login_password=", Password, "&cookieuser=1&s=&securitytoken=guest&do=login&vb_login_md5password=&vb_login_md5password_utf=" }))
If Http.ResponseValue.Contains(("Thank you for logging in, " & Username)) Then
Http.GetResponse("http://www.website.com/forum/usercp.php")
Return True
End If
Return False
End Function
This is what I've already done:
- (IBAction)loginButton:(id)sender {
NSURL *loginURL = [NSURL URLWithString:#"http://www.website.com/forum/login.php?do=login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:loginURL];
[request setRequestMethod:#"POST"];
[request setUseKeychainPersistence:YES];
[request addPostValue:[self.usernameField stringValue] forKey:#"vb_login_username="];
[request addPostValue:[self.passwordField stringValue] forKey:#"&vb_login_password="];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startSynchronous];
[request setUseSessionPersistence:YES];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSLog(#"Request failed: %#",[request error]);
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Submitted form successfully");
NSLog(#"Response was:");
NSLog(#"%#",[request responseString]);
}
But it does not work..
I get a reply back but not as a member.
P.S. It's about a vBulletin Forum
Sorry for my bad english..
Thanks in advance!

Hard to try to reproduce with no server to test. However two things:
lib which you use is depreciated, consider moving for other (for example AFNetworking)
in second parameter you have "&vb_login_password=" I believe there should be no '&' character. Also try to remove '=' at end.
If there is no HTTPS you can use wireshark to check packets from program which work, and from your version. Then compare both request and seek for differences.

It now works. I've added some more entries.
[request addPostValue:#"1" forKey:#"cookieuser"];
[request addPostValue:#"login" forKey:#"do"];
[request addPostValue:#"" forKey:#"s"];
[request addPostValue:#"guest" forKey:#"securitytoken"];
[request addPostValue:#"" forKey:#"vb_login_md5password"];
[request addPostValue:#"" forKey:#"vb_login_md5password_utf"];
[request addPostValue:[self.passwordField stringValue] forKey:#"vb_login_password"];
[request addPostValue:[self.usernameField stringValue] forKey:#"vb_login_username"];
I now get the HTML code from the forum back to a point where it says "Thank you for logging in, Username".

Related

How do i set multiple http header using sessionManager (AFNetworking)

I have searched through various stackoverflow questions and I got answer but using NSMutableURLRequest as there is one method - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field; which can be called over requestObject only.
How do I add value using _sessionManager.requestSerializer ?Or any work around. Here is the code which I am using for session configuration.
- (void)configureSesionManager {
_sessionManager = [AFHTTPSessionManager manager];
_sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
_sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
_sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
_sessionManager.requestSerializer.timeoutInterval = 360;
if ([GSCommonUtil isUserLoggedIn]) {
authenticationHeader = [NSString stringWithFormat:#"Bearer %#",[GSCommonUtil retriveValueFromUserDefaults:kNSUserAuthenticationToken]];
[_sessionManager.requestSerializer setValue:authenticationHeader forHTTPHeaderField:#"Authorization"];
}
[_sessionManager.requestSerializer setValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[_sessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// I have to add one more HTTPHeader for #"Accept". How could I achieve it.
NSLog(#"Done with Session Manager Configuration!");
}
The Accept header takes a comma separated list, so something like this should work:
[_sessionManager.requestSerializer setValue:#"application/json, application/xml" forHTTPHeaderField:#"Accept"];
Obviously replace application/xml with whatever you need.

OCMock: Setting expectations on properties

How do I set an expectation on a property of an instance?
Let's say I have the following code:
id request = OCMClassMock([NSMutableURLRequest class]);
And I want to make sure that, in my implementation, the HTTPMethod property is set to #"Get", how would my test verify this?
Try something like this:
- (void)testNSURLConnection
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.stackoverflow.com"]];
[request setHTTPMethod:#"POST"];
id connectionMock = OCMClassMock([NSURLConnection class]);
OCMStub([connectionMock connectionWithRequest:[OCMArg checkWithBlock:^BOOL(NSMutableURLRequest *request) {
XCTAssertTrue([request.HTTPMethod isEqualToString:#"GET"]);
return YES;
}] delegate:OCMOCK_ANY]);
[NSURLConnection connectionWithRequest:request delegate:nil];
}
This test will fail until your change #"POST" to #"GET" which is, I believe, what you want.

URL reachablility - false positive

There are a ton of "false positive" posts, though none appear to match my situation. (Most are talking about internet connection errors..)
As with everyone almost else, I just want to determine whether a specific URL is valid.
Now, I'm dealing with subdomains, and it works great as long as I choose a valid domain. If I choose an invalid subdomain, I get a false positive. Using a browser to test reveals that my ISP gives me a really annoying suggestions page if I type in a URL that doesn't exist.
Any way to validate that the responding server IS actually at the URL I asked for?
My Code:
-(BOOL) canConnectToURL:(NSString * )sURL {
BOOL bSuccess = NO;
if (![txtSubDomain.text.lowercaseString isEqual: #"www"]){
NSLog(#"canConnectToURL(%#)",sURL);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: sURL]];
[request setHTTPMethod: #"HEAD"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
NSLog(#"URL: %#",sURL);
NSLog(#"data: %#",response);
bSuccess = ([(NSHTTPURLResponse *)response statusCode] == 200);
}
return bSuccess;
}
I believe you can attach a delegate to your NSURLRequest that handles the method connection:willSendRequest:redirectResponse: in the NSURLConnectionDataDelegate protocol, and catch it there.
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLConnectionDataDelegate_protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40011348-CH1-SW9

JSON Parsing Error in ios

I want to fetch some data from some url and print result in nslog.
I am passing URl and want to fetch result in log only.
I have used this code :
-(void)GETJSONDATA
{
NSString*lu=#"tmp";
NSString *requestString = [[NSString alloc]init];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString: #"http://assessments.tlisc.org.au/webservices/questions/getbytaskpart.php?jsoncallback=?&token=1726204214321678|xTAieBBJoDaWmBsG1stxfq4zLO4&taskpartid=1"]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Test" message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
NSDictionary *results = [responseString JSONValue];
NSLog(#"results=%#",results);
}
}
It is showing me this error :
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x6a42be0 {NSLocalizedDescription=Unexpected end of string}"
Can anybody point me error?
In response string , it is showing null value.
I don't know the actual error.
it is working fine in browser but when I parse it it is showing this error....Is there anyway through which I can modify the url and get result ...i have checked my code with different url.and it is working proper..
I think I was using the same library as you're using here, and for some unexplained reason it just failed on a particular google api, sometimes getting results but usually failing. There appeared to be nothing wrong with the code.
In the end I went with the inbuilt NSJSONSerialization ( http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html ) object and it hasn't failed since. I wasn't even aware there was JSON support built in (from iOS5 apparently).
I ran the two calls and processed them side by side, the external library continually failed. The internal methods worked fine.
Since I'm a beginner and the docs (above) don't really help me a lot, I used this tutorial http://www.raywenderlich.com/5492/working-with-json-in-ios-5 to get my head around it
As the error told you: the incoming JSON is not well-formed. Making a simple GET request to the URL you are using, I'm getting a JSON that is malformed, i.e. it is not valid JSON. I guess posting data to this URL returns the same format with actual data in it (not null).
Making use of a simple JSON Validator, I'm getting this
Parse error on line 5: ... "Description": "\n\tQuestion Numbe
-----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
Check your url in a browser. See the result. Your result's Structure should be like the same as JSON. if there is any other extra word in start of the json means. you should check your php code.
You have got HTML tags within your strings. Paragraph marks like
<p> and </p>
And these are not properly escaped. However, I do not know by hard wether the less than sign and greater than sign need to be escaped in JSON but apparently they are creating the issue.
Using google I find statements for both. However, some site suggests escaping < with \u003c and > with \u003e. that should do the trick.
I tried to validate the output from
http://assessments.tlisc.org.au/webservices/questions/getbytaskpart.php?jsoncallback=?&token=1726204214321678|xTAieBBJoDaWmBsG1stxfq4zLO4&taskpartid=1
It seems to be valid though if the <p> and </p> ist not interpreted by the bowser. (I was lookint to the "page source").
However, when escaped the string is still valid and encodes to the same result.
If this is not your issue, then please provide the output of your
NSLog(#"Resp : %#",responseString);

ASIFormDataRequest - iOS Application. How do I RETRIEVE a post variable

So I have this url that leads to a .php
So far I managed to retrieve every single thing except the actual XML that I want. the XML is stored in a variable called _xml.
if($this->outMethod=="" || $this->outMethod=="POST") //Default to POST
{
$_POST["_xml"] = $_xml;
}
So I've already set the outMethod to POST but I don't understand how to retrieve the value within _xml.
- (void)grabURLInBackground
{
NSLog(#"grab url in background");
NSURL *url = [NSURL URLWithString:#"xxxxxxxxxxx"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"POST" forKey:#"outMethod"];
[request setPostValue:#"1" forKey:#"Entity_ID"];
[request setDelegate:self];
[request startAsynchronous];
NSLog(#"end of grabUrlInBackgroun");
}
don't worry the URL is right I just don't want to post it.
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"A");
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
if(responseString)
{
NSLog(#"responseData is not null");
}
NSLog(#"response string: %#", responseString);
//NSLog(#"%#", responseString);
}
What I get back is that the request is good, but there is no response in responseString. This is because my php does not want to print out any of the XML on screen in HTML but it stores the result in the variable _xml sent via post "$_POST["_xml"] = $_xml
My question is, how do I get back that xml variable? Isn't there a method available within the ASIHTTPRequest library? I am using ASIFormDataRequest class not ASIHTTPRequest.
You have to print you variable in the php-file:
if($this->outMethod=="" || $this->outMethod=="POST") //Default to POST
{
echo $_xml;
}
A HTTPRequest (and the ASIFormDataRequest as well) isn't interested in any variables you declare in your *.php file. It only returns the string you actually print.