从android发出JSON请求

时间:2011-03-16 10:41:57

标签: java android objective-c json

我有以下Objective-c代码可以完成我需要为android做的事情,但不知道如何去做。我需要在web服务器上访问一个php文件,它将返回一个JSON字符串(我认为是字典吗?)。以下是我对iPhone版本的代码:

+ (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;     
}

我应该在哪里寻求帮助在Android中复制这个?我真的没有任何有意义的JSON经验,特别是在Java / Android中没有。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:4)

以下是从Web Service读取并解析JSON对象的Android活动的代码:

public void clickbutton(View v) {
    try {
        // http://androidarabia.net/quran4android/phpserver/connecttoserver.php

        // Log.i(getClass().getSimpleName(), "send  task - start");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        //
        HttpParams p = new BasicHttpParams();
        // p.setParameter("name", pvo.getName());
        p.setParameter("user", "1");

        // Instantiate an HttpClient
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "http://10.0.2.2:8080/sample1/" + 
                     "webservice1.php?user=1&format=json";
        HttpPost httppost = new HttpPost(url);

        // Instantiate a GET HTTP method
        try {
            Log.i(getClass().getSimpleName(), "send  task - start");
            //
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("user", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            // Parse
            JSONObject json = new JSONObject(responseBody);
            JSONArray jArray = json.getJSONArray("posts");
            ArrayList<HashMap<String, String>> mylist = 
                   new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < jArray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = jArray.getJSONObject(i);
                String s = e.getString("post");
                JSONObject jObject = new JSONObject(s);

                map.put("idusers", jObject.getString("idusers"));
                map.put("UserName", jObject.getString("UserName"));
                map.put("FullName", jObject.getString("FullName"));

                mylist.add(map);
            }
            Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Log.i(getClass().getSimpleName(), "send  task - end");

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

有关详细信息,请参阅http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php