I have got the following objective-c code which does what I need to do for android but have no idea how to go about it. I need to access a php file on a webserver which will return a JSON string (Dictionary I think?). Below is the code I have for the iPhone version:
+ (NSDictionary *)getNewMission:(int)maxID
{
NSString *serverUrl = @"http://www.website.com/api/api.php";
NSString *methodString = [NSString stringWithFormat:@"\"method\":\"getNewItem\",\"max_item_id\":\"%d\"", maxID];
NSString *postStr = [NSString stringWithFormat:@"json={%@,\"key1\":\"%@\",\"key2\":\"%@\"}", methodString, KEY_1, KEY_2];
return [JsonManager handleJSONRequest:postStr baseURL:serverUrl];
}
+ (NSDictionary *)handleJSONRequest: (NSString*)postString baseURL:(NSString*)baseUrl
{
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:baseUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSDictionary *results = [data JSONValue];
[data release];
return results;
}
Where should I be looking to help with replicating this in android? I really don’t have any meaningful JSON experience especially not in Java/Android. Any help is appreciated.
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
For more details see http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php