Hi I’m writing an app for both iOS and Android to interface with a druapl site. I’m trying to allow users to login to the website and then save the data from successful logins in the preferences of the app. Below I was able to successfully do what I wanted in Cocoa but I have been unable to get it to work in Java. Both code snippets are below. Any help with the java would be greatly appreciated.
I’m just not getting any response at all from the java the response comes back as an empty string when it should be a long JSON response.
Cocoa Login (Working)
NSURL *url = [NSURL URLWithString:@"http://examplesite/api/rest/user/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSData *requestBody = [[NSString stringWithFormat:@"username=%@&password=%@",[userField text],[passField text]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
Java Login (Not Working)
class loginTask extends AsyncTask<Void, Void, Void> {
HttpResponse response;
public loginTask() {
}
@Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://examplesite/api/rest/user/login");
try {
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "password"));
post.setEntity(new UrlEncodedFormEntity (formparams));
response = client.execute(post);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Void unused) {
//TODO finish the activity
try {
Toast.makeText(Login.this, EntityUtils.toString(response.getEntity(), "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There’s things for this like. Drupal iOS sdk and dandy for android