POST requests not working in Swift with Alamofire - php

I'm trying to send data from a Swift app to a backend in PHP.
To test, I make a request via POST with Alamofire and print the request method as a response from the Server.
let URL_USER = "myurl"
var sampleRequest = URLRequest(url: URL(string: URL_USER)!)
sampleRequest.httpMethod = HTTPMethod.post.rawValue
AF.request(sampleRequest).uploadProgress{ progress in }.response(){
response in
if(response.data != nil) {
print(String(bytes: response.data!, encoding: .utf8) as Any)
}
else {
print("Error")
}
}
The PHP script:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo 'OK';
}
else {
echo 'Wrong request method';
}
The server response is always Wrong request method
The same also occurs using the post parameter directly inside the Alamofire call, with this code:
AF.request("myurl", method: .post).response {...}
Any attempt to send the request via POST, even without Alamofire, fails and the server replies saying that the request is of type GET.
This occurs both on the simulator and on a real device, without any proxy.
The URL I call is based on https
UPDATE
To test the basic functioning of Alamofire with the function of their documentation I tried this code:
AF.request(URL_USER, method: .post).response {
response in
if(response.data != nil) {
print(String(bytes: response.data!, encoding: .utf8) as Any)
}
else {
print("Error")
}
}
But the response still goes Wrong request method and Proxyman says it's of type GET

The problem was caused by a redirect in the URL.
For some reason https://mysite.tld was redirecting to https://www.mysite.tld using GET. In this way all the parameters and the type of request were altered. I solved the problem by making the request directly to https://www.mysite.tld.
To find out the redirect I used Proxyman.

Related

Why isn't my php json_encode not serializable with .responseJSON in alamofire?

I'm having some trouble with serialization on a JSON response on my iOS app from my server, its a PHP back-end. My app sends a post request with the appropriate parameters, validates them, puts the results in an array, and encodes it in. Now that's not the problem, code works fine. However, its the link between them. Look at the PHP code below.
echo json_encode($array)
Now coming to xcode, I'm using alamofire to send the request as seen in the code below
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseString { response in
print(response)
}
}
As you can see its in .responseString because I apparently if I use .responseJSON it throws a code=3480 error and I want to get specific data from my own response JSON. I tried other ways to fix this online, but they all choose the .responseString option.
Why is this happening? Are the JSON types incompatible? Is there a secret to this?
I just want to get specific data from my JSON response such as "message" and its not possible when i get a string... Any help is appreciated!
I'm using Alamofire 4.3
Try following so Alamofire will run the response data through JSONSerialization, depending on the type of JSON response you can use either json as? [String : Any] or json as? [[String : Any]]
Alamofire.request(URL, method: .post, parameters: parameters).responseJSON { response in
guard response.error == nil, let json = response.result.value else {
print("Error: \(response.error?.localizedDescription ?? "no content")")
return
}
if let jsonDict = json as? [String : Any] {
print(jsonDict)
} else if let jsonArray = json as? [[String : Any]] {
print(jsonArray)
}
}
Have you tried printing the response.value to check it it's a valid JSON?

retrofit2 sending a PUT request method is wrong for PHP

I am trying to send a PUT request method from my Android app to my PHP endpoint but in my endpoint the PUT request is not recognized as a PUT request so I return Request method is wrong! message from my endpoint.
Android interface and request execution
Interface for activation
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice();
Executing the request
DeviceRegistryAPI registryAPI =
RetrofitController.getRetrofit().create(DeviceRegistryAPI.class);
Call<DeviceRegistry> registryCallback = registryAPI.registryDevice();
response = registryCallback.execute();
With this I am expecting a response but I am getting my endpoint error message.
My PHP endpoint
if($_SERVER['REQUEST_METHOD'] == "PUT"){
//doing something with the data
} else {
$data = array("result" => 0, "message" => "Request method is wrong!");
}
I don't know why the $_SERVER['REQUEST_METHOD'] == "PUT" is false but I wonder if I am missing something on Retrofit 2.
More Info.
I am using Retrofit2.
Update 1: Sending json into the body
I am trying to send a json using the body.
It is my json:
{
"number": 1,
"infoList": [
{
"id": 1,
"info": "something"
},
{
"id": 2,
"info": "something"
}
]
}
There are my classes:
class DataInfo{
public int number;
public List<Info> infoList;
public DataInfo(int number, List<Info> list){
this.number = number;
this.infoList = list;
}
}
class Info{
public int id;
public String info;
}
I changed the PUT interface to this:
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice(#Body DataInfo info);
But I am getting the same problem.
Update 2: Do I need Header
I have this header in my REstfull client:
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Do I need to put this on my request configuration? How do I do that if I need it?
Update 3: checking the request type of my sending post.
Now I am checking the type of the request. Because I am having the same problem with the PUT/POST requests. So If can solved the problem with the put maybe all the problems will be solved.
When I execute the request and asking and inspect the request it is sending the the type (PUT/POST) but in the server php only detect or GET?? (the below example is using POST and the behavior is the same)
Call<UpdateResponse> requestCall = client.updateMedia(downloadItemList);
Log.i("CCC", requestCall .request().toString());
And the output is a POST:
Request{method=POST, url=http://myserver/api/v1/media/updateMedia.php, tag=null}
so I am sending a POST (no matter if I send a PUT) request to the sever but why in the server I am receiving a GET. I am locked!!! I don't know where is the problem.
Update 4: godaddy hosting.
I have my php server hosting on godaddy. Is there any problem with that? I create a local host and everything works pretty good but the same code is not working on godaddy. I did some research but I didn't find any good answer to this problem so Is possible that godaddy hosting is the problem?
PHP doesn't recognize anything other than GET and POST. the server should throw at you some kind of error like empty request.
To access PUT and other requests use
$putfp = fopen('php://input', 'r'); //will be a JSON string (provided everything got sent)
$putdata = '';
while($data = fread($putfp, filesize('php://input')))
$putdata .= $data;
fclose($putfp);
//php-like variable, if you want
$_PUT = json_decode($putdata);
did not tested, but should work.
I guess the problem is that you don't pass any data along with PUT request, that's why PHP recognizes the request as a GET. So I think you just need to try to pass some data using #FormUrlEncoded, #Multipart or probably #Body annotations
To add header in your retrofit2 you should create an interceptor:
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException
{
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Content-Type", "application/x-www-form-urlencoded");
ongoing.addHeader("Accept", "application/json");
return chain.proceed(ongoing.build());
}
};
and add it to your client builder:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
PHP recognises 'PUT' calls. Extracted from PHP.net:
'REQUEST_METHOD' Which request method was used to access the page;
i.e. 'GET', 'HEAD', 'POST', 'PUT'.
You don't need to send any header if your server isn't expecting any
header.
Prior to use Retrofit or any other networking library, you should check the endpoint using a request http builder, like Postman or Advanced Rest Client. To debug the request/response when running your app or unit tests use a proxy like Charles, it will help you a lot to watch how your request/response really looks.

How to establish a connection to a web server with NSURL in which variables can be passed securely via URL to PHP script

I am using Swift's NSURL function to connect to a PHP script that I can use to interact with a MySQL database. Everything is running smoothly except for the insecurity of the variables passed in the URL via POST. If someone were to intercept these variables it would pose an enormous security risk to my application. I have researched the subject extensively however I have hit a wall. Is an SSL certificate enough to secure the URL? I am not passing the variables through the literal URL but a POST method. As far as I know, the SSL certificate provides security for the data passed AFTER the initial connection (meaning that the data originally passed via POST and the URL are not secure). So essentially, how do I go about passing variables to a web server securely?Here is the code I am using to establish the connection:
let myUrl = NSURL(string: "http://testsite.com/login.php”)
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = “username=bob&password=123"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
if let responseData = data {
let responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
}
}
} else {
self.sendAlert("Error", message: "Unable to establish connection")
}
}
You can refer to raywenderlich tutorials for setting up the iOS part of it. This tutorial is for connection between ruby rails and swift. It has sign in, sign up and token system, it also includes encryption.
The tutorial uses httpBody to pass the information, you can stick with that or modify to header instead to personalise your codes as required.
request.addValue("bob", forHTTPHeaderField: "username")
request.addValue("123", forHTTPHeaderField: "password") // add AES Encryption.
Also, you can implement a token system instead of passing your username and password. You would however have to pass it initially to get the token.

Sending a request to a php web service from iOS

I have a question relating to sending a POST request from an iOS app to a web service written in php, that will ultimately query a MySQL database.
tldr: How do I view the contents of the POST variables directly in the browser window, without refreshing?
Long version:
I had written my Swift code in Xcode, with NSURLSession, request, data etc.
I had a php web page set to var_dump($_POST); so that I could check that the data was sent in correctly (my data was a hard-coded string in Xcode for testing purposes).
I couldn't for the life of me figure out why I kept getting empty POST variables, until I decided to add a test query statement to my web page binding the POST variable. Lo and behold, the query ran successfully and my table updated.
I now realise that the reason I thought the POST variable was empty was because I was refreshing the web page in order to see the results of my var_dump. I now also know that this was deleting the POST data, because when I repeated this action with the query statement, my table was getting NULL rows.
My question is how do I view the contents of the POST variables directly in the browser window, without refreshing? I know this must be a real noob goose chase I've led myself on... but I am a noob.
Thank you
You would need to modify the service itself to output those values in some way. If this is strictly for debugging, you are better off having the service write out to a log file instead. If this is part of the requesting applications call and the data needs to be displayed to the user, the service should probably return either an XML or JSON string response that your application can parse. Otherwise, you can use Fiddler to monitor your web traffic.
Of course overtime you refresh the page you just get an empty variable.
This is what I used to test if my code was working:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
testPost() // this function will test that the code is sending the variable to your server
return true
}
func testPost() {
let variableToPost = "someVariable"
let myUrl = NSURL(string: "http://www.yourserver.com/api/v1.0/post.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "variable=\(variableToPost)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print(error)
return
}
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json{
let result = parseJSON["status"] as? String
let message = parseJSON["message"] as? String
if result == "Success"{
//this should return your variable
print(message)
}else{
// print the message if it failed ie. Missing required field
print(message)
}
}//if parse
} catch let error as NSError {
print("error in registering: \(error)")
} //catch
}
task.resume()
}
then your php file will only check if there is no empty post and return the variable as JSON:
post.php
<?php
$postValue = htmlentities($_POST["variable"]);
if(empty($postValue))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
} else {
$returnValue["status"] = "success";
$returnValue["message"] = "your post value is ".$postValue."";
echo json_encode($returnValue);
}

Swift: How to use NSURLSession to query external database?

I am writing this question because I am in a big difficulty in understanding how to implement a simple basic authentication login with Swift.
The first screen of my app is a simple form with text fields (username and password) and a Sign In button. In my LoginViewController.swift file I linked the button to this:
#IBAction func doLogin(sender : AnyObject) {
}
The probem now is that I don't know how to go on. I have a local server in MAMP where there is this file.php querying a database and which works perfectly:
<?php
$deep="";
require_once($deep."class/config.php");
$sistema = new config($deep);
if( isset($_GET["username"]) && isset($_GET["password"]) ) {
$username=mysqli_real_escape_string($sistema->dbConn,$_GET["username"]);
$password=mysqli_real_escape_string($sistema->dbConn,$_GET["password"]);
$userL=$sistema->user->allAdmin("WHERE username='".$username."' AND password='".$password."' ");
echo json_encode($userL);
}
?>
So how can I perform a GET request to this file? I suppose I need to create a URL with user data like this form:
http://localhost:8888/excogitoweb/loginM.php?username=lorenzo&password=lorenzo
but then I don't know how to go on. How can I perform this request to retrieve that JSON content? And how can I check that JSON content in order to understand if the sign in procedure has succeeded or has not?
I have watched many tutorials in youtube, overall this but even if I copy the code they show I always get compilation errors...
for a "normal" GET request you need a NSURLRequest with your url... Its just like this:
if let requestURL: NSURL = NSURL(string: "http://localhost:8888/excogitoweb/loginM.php?username=lorenzo&password=lorenzo") as NSURL? {
let urlRequest: NSURLRequest = NSURLRequest(URL: requestURL)
let urlSession = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseJSON: [String: String] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? [String: String] {
///Here you can handle the responded JSON
}
})
urlSession.resume()
}
Don't forget, you are on a background Task when you handle the responded JSON... If you want to do some UI Stuff there you will need to dispatch it to the mein queue
Also a would recommend you doing HTTP POST instead of HTTP GET for such things
UPDATE
if let responseJSON: [[String: String]] = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? [[String: String]] {
///Here you can handle the responded JSON
}

Categories