I am sending reguest to webserver in this function:
-(void)getData
{
NSURL *url = [NSURL URLWithString:#"http://10.10.10.10/application.php"]; //some address
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.delegate = self;
[request setPostValue:#"6577098" forKey:#"serial_number"];
[request startAsynchronous];
}
Then on server part in application.php :
<?php
//$serial_number from $_POST["serial_number"];
$serial_number = $this->getString('serial_number', 64);
$stmt = $this->pdo->prepare('SELECT S.DateTime, SN.Name FROM States S LEFT JOIN StateNames SN on SN.ID=S.State_ID WHERE S.SerialNumber = ?');
$stmt->execute(array($serial_number));
$states = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = array();
foreach ($states as $state)
{
$result[] = $state;
}
sendResponse(200, json_encode($result));
?>
This part works when I try it from browser, it works and I get this:
[{"DateTime":"2013-05-15 10:22:11","Name":"No water"},{"DateTime":"2013-05-13 14:55:31","Name":"Water"}]
Then back to process it in Xcode:
-(void)requestFinished:(ASIHTTPRequest *)request
{
if (request.responseStatusCode == 200)
{
NSString *responseString = [request responseString];
NSLog(#"%#",responseString); //if I try this nothing happened
}
}
I think I have to do something with JSON.
I thing I have bad response on my request. But I have responceStatusCode 200.
Can anyone help me? I didn't find what's wrong.
Thanks
I would need specifics to tell you what server settings you need to adjust. My next best advice - debug line by line. For example in php file, do:
$serial_number = $this->getString('serial_number', 64); //there I get serial_number from $_POST["serial_number"];
echo $serial_number; die;
// ...
at this point if you run your app again, you should see the serial # printed in -(void)requestFinished:(ASIHTTPRequest *)request, if nothing breaks up to here. If you do see it, remove echo and die, move on
//...
$stmt = $this->pdo->prepare('SELECT S.DateTime, SN.Name FROM States S LEFT JOIN StateNames SN on SN.ID=S.State_ID WHERE S.SerialNumber = ?');
$stmt->execute(array($serial_number));
$states = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($states); die;
// ...
if no responce there, this might mean that you don't have PDO driver installed with your php.
If the next line sendResponse(200, json_encode($result)); breaks it, then my guess is that your php installation lacks json module.
Related
I'm struggling to believe this is so difficult but after spending a couple of hours trying to figure it out, here I am asking the hive mind for help!
My question is very similar to this one however the answers in there don't help me as I have no keys in my form. I basically want to send a text .plist file from a PC to my app. The HTML on the page is this ..
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" id="config" name="config" accept=".plist" size=40>
<input type="submit">
</form>
This gives a very simple form with a chose file button and a submit button. I have confirmed with Wireshark that the file is attached to the form and the thing is POSTed to the GCDWebServer in my app. I can also see the following confirming the body data as the file upload is processed by the web server:
[DEBUG] Connection on socket 21 preflighting request "POST /upload" with 2045 bytes body
[DEBUG] Connection on socket 21 processing request "POST /upload" with 2045 bytes body
My POST method for handling the file is this:
[_webServer addHandlerForMethod:#"POST"
path:#"/upload"
requestClass:[GCDWebServerRequest class]
processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
NSString *type = [(GCDWebServerRequest*)request contentType];
NSInteger length = [(GCDWebServerRequest*)request contentLength];
BOOL hasBody = [(GCDWebServerRequest*)request hasBody];
NSString *description = [(GCDWebServerURLEncodedFormRequest*)request description];
NSLog(#"\r\nType: %#\nLength: %lu\nHas Body: %#\nHeaders: %#\nConfig: %#", type, length, hasBody?#"YES":#"NO", description, #"");
return [GCDWebServerDataResponse responseWithHTML:#"TODO UPLOADED CONFIRMATION"];
}];
I can get the content type, content length, a boolean confirmation there is a body attached, all the headers and description of the boundaries etc. But I cannot for the life of me figure out how to get the actual body content. I don't wish to save it as a file I simply want it as an NSString so I can parse it and then save the settings inside my app.
A few things I have tried:
//NSData *data = [(GCDWebServerRequest*)request data];
//NSString *config = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//NSString *config = [(GCDWebServerMultiPartFormRequest*)request files];
//NSString *config = [[(GCDWebServerURLEncodedFormRequest*)request arguments] objectForKey:#"filename"];
The NSData one looks the most likely to me but the app crashes when calling that. If anyone has any idea how I might access the body of this posted content I would be extremely grateful!
Thanks in advance!
Plasma
You'll want to use GCDWebServerMultiPartFormRequest. There's an an example here in https://github.com/swisspol/GCDWebServer/blob/master/Mac/main.m#L257.
I am making an app based on broadcasting I am using videoCore Lib for Broadcast for that I am using below code to start rtmp session
[_session startRtmpSessionWithURL:urlForStream
andStreamKey:streamID];
urlForStream is url of wowza server like rtmp://some.tv/some/username/username/randamvalue
that Randam value is don't want to override my videos every time so i am using that url and now My Problem is VCSessionState class state is not changing it is not coming to started state and I am getting the Error here is streamsessio.mm class and [NSRL(m_runLoop) run]; i don't kow where i miss please help me out
Considering from my experience of having created my own RTMP protocol library, I thought you have to separate the URL into two parts: tcUrl and stream key. In your case, the random value is likely to be a stream key.
NSString *tcUrl;
NSString *stream;
separateRtmpUrl(urlForStream, &tcUrl, &stream);
[_session startRtmpSessionWithURL:tcUrl andStreamKey:stream];
The definition of the separateRtmpUrl function can be like this.
static void separateRtmpUrl(NSString *baseUrl, NSString **tcUrl, NSString **stream)
{
NSURL *url = [NSURL URLWithString:baseUrl];
*stream = url.pathComponents.lastObject;
*tcUrl = [NSString stringWithFormat:#"%#://%#%#", url.scheme, url.host,
[NSString pathWithComponents:
[url.pathComponents subarrayWithRange:
NSMakeRange(0, url.pathComponents.count - 1)]]];
if (url.query) {
*stream = [#[*stream , url.query] componentsJoinedByString:#"?"];
*tcUrl = [#[*tcUrl , url.query] componentsJoinedByString:#"?"];
}
}
I am learning Jersey and stumbling from one issue to another. I just got the service to work from Java client (after some help from someone here). The service class is as follows:
#Path("/user")
public class UserService extends AbstractService {
private static final NouLogger logger = NouLogger
.getLogger(UserService.class);
#Path("fbregister")
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createNewFBUser(#FormParam("fbuserid") String userid,
#FormParam("fbmailid") String emailId,
#FormParam("fbfullname") String fullName,
#FormParam("fbusertoken") String userToken,
#Context HttpServletResponse servletResponse) throws IOException,
DatabaseException {
final String methodName = "createNewFBUser";
User user = new User();
user.setEmail(emailId);
user.setName(fullName);
user.setFacebookSecret(userToken);
Session session = null;
try {
session = getSession();
} catch (DatabaseException e) {
final String message = "Error occurred while fetching session.";
logger.error(methodName, message, e);
e.printStackTrace();
}
UserDAO userDAO = DAOFactory.DEFAULT.buildUserDAO();
Transaction txn = session.beginTransaction();
userDAO.save(user);
txn.commit();
closeSession();
return user.getId().toString();
}
}
This works fine when I call it from Java client. But when I call it from iOS code, I get all the null values for all the parameters. The iOS code is as below:
// To encode parameter.
NSString *fb_userid = [user objectForKey:#"id"];
NSString *fb_mailid = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)[user objectForKey:#"email"], NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 ));
NSString *fb_fullname = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)user.name, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 ));
NSString *fbAccessToken = [[[FBSession activeSession] accessTokenData] accessToken];
NSLog(#"user = %#", user);
NSLog(#"fb_userid = %#", fb_userid);
NSLog(#"fb_mailid = %#", fb_mailid);
NSLog(#"fb_fullname = %#", fb_fullname);
// To send url Request.
NSString *url1 =[NSString stringWithFormat:#"http://myip:8080/nou/rest/user/fbregister?fbuserid=%#&fbmailid=%#&fbfullname=%#&fbusertoken=%#", fb_userid, fb_mailid, fb_fullname, fbAccessToken];
NSURL *url = [NSURL URLWithString:url1];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
theConnection1 = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Any idea why this is happening? I put it on remote debug, I could see the method being invoked also, my DB entry was created but all the null values were put in it. Help me solve this issue.
EDIT:
I tried sending just one parameter 'id' and it did not work either.
In your java code, you are accepting parameters as FormParam but while posting you are sending it as part of query string from the client code. So either:
Change the FormParam in server code to QueryParam
or Change the client code to send it as post params. Here is an example:
How to simulate HTTP form (POST) submit on iOS
I am trying to upload an image file to the server. I am applying the example from https://github.com/valentinradu/WhiteRaccoon
Here is the code:
UIImage *image = [UIImage imageNamed:#"hotel1.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 0);
WRRequestUpload * uploadImage = [[WRRequestUpload alloc] init];
uploadImage.delegate = (id)self;
//for anonymous login just leave the username and password nil
uploadImage.hostname = #"***.***.***.***";
uploadImage.username = #"-------";
uploadImage.password = #"-------";
//we set our data
uploadImage.sentData = imageData;
//the path needs to be absolute to the FTP root folder.
//full URL would be ftp://xxx.xxx.xxx.xxx/space.jpg
uploadImage.path = #"/android_images/image.jpg";
//we start the request
[uploadImage start];
but it gives error -[WRRequestListDirectory stream:handleEvent:] [Line 1004] Unknown error!
am I missing anything. Please help me out.
in the uploadimage.hostname property try skipping the ftp:// part and enter the host address alone for eg: "qwerty.com" instead of "ftp://qwerty.com" , it solved for me, and make sure that the authentication details given are correct. cheers !!
if you are using BlackRaccoon,
Please make one line change in BRRequest.m file.
In - (id)initWithDelegate:(id<BRRequestDelegate>)aDelegate Function.
Change
self.passiveMode = YES;
to
self.passiveMode = NO;
And it will work....
That change worked for me.
My requested URL is https://api.instagram.com/v1/media/MYMEDIA_ID/comments?access_token=MYTOKEN&text=MYTEXT
I get a reply like this:
{
meta = {
code = 400;
"error_message" = "Missing 'text'";
"error_type" = APIInvalidParametersError;
};
}
In the Instagram document it says the comment API takes two parameters: text and access_token. I have provided both, and I get the error saying text is missing.
I have tried with different symbols instead of & but nothing works. Does anybody have experience on how the text parameter should appear on the requested URL?
Thanks a lot !
i am using hybridauth, and here is the code, it is working..
function setUserComment($post_id, $message)
{
$flag = 0;
$parameters = array("text" => $message);
$response = $this->api->post( "media/$post_id/comments", $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Comment failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
else{
$flag = 1;
}
return $flag;
}
To add comments to Instagram you need to post the text it shouldn't be part of the URL. The Instagram API documentation provides an example using CURL:
curl -F 'access_token=1084932.f59def8.deb7db76ffc34f96bada217fe0b6cd9a' \
-F 'text=This+is+my+comment' \
https://api.instagram.com/v1/media/{media-id}/comments
So neither the access_token or the text are part of the URL just POST data.
Just add text=MYTEXT to your request's HTTPBody.
Here is sample code:
NSMutableURLRequest *apiRequest = [[NSMutableURLRequest alloc] initWithURL:apiURL];
apiRequest.HTTPMethod = #"POST";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"text=%#", MYTEXT] dataUsingEncoding:NSUTF8StringEncoding]];
apiRequest.HTTPBody = body;
[NSURLConnection sendAsynchronousRequest:apiRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// Handle the response.
}];
you need to change the content type of the request ContentType="comment"
I believe the key here is ContentType header. At least nothing worked for me until I started to define it.
If you set "ContentType": "multipart/form-data" you need to set up quite a complex body content as described here:
https://dotnetthoughts.net/post-requests-from-azure-logic-apps/
I found much easier path:
Set your header "Content-Type": "application/x-www-form-urlencoded"
and then you can set your request body as simple as key=url_escaped(value):
text=My%20comment