Adding secure parameters to web service calls Android AND XCode!
When you need to get information from a web service for your mobile application (which is almost all you ever do) you must have the ability to add $_POST information and send the request securely. Apple’s Swift language insists on this for every call to an external URL. Android is not so strict mainly because there are about a hundred ways to do this in Android and very few in Swift.
As a for instance let’s go back to the login form I created for my Android Student app:
Once you have privately read in the values from the form fields you have to find some way to securely transmit these to the webserver to have them checked and keys to be returned. Adding the parameters to the URL as GETs is inappropriate as the full URL will be shown in the web server logs.
This isn’t a simple task in Android, indeed I wouldn’t have managed without stackoverflow.com.
The url parameters are added to a DataOutputStream object then the response read into an InputStreamReader object and finally loaded into a String to be parsed (the responses are XML).
Android
String url = "https://www.yoursecuresite.com";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Language", "en-GB,en;q=0.5");
String urlParameters = "login=yourusername&password=yourpassword";
// Send post request
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
In Swift it it a bit simpler. The parameters are added to the HTTP body without the need to join input and output streams (this is probably happening but you are, thankfully, abstracted from it by XCode):
Swift
let url = URL(string: "https://
www.yoursecuresite.com")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "login=yourusername&password=yourpassword"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request)....