2011-03-16 62 views
0

我已經得到了下面的目標c代碼,它做了我需要爲android做的事但不知道如何去做。我需要訪問一個Web服務器上的PHP文件,它將返回一個JSON字符串(字典,我認爲?)。以下是我對iPhone版本的代碼:從android中製作JSON請求

+ (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中。任何幫助表示讚賞。

+0

請選中該[鏈接](HTTP:// www.instropy.com/2010/06/14/reading-a-json-login-response-with-android-sdk/) – 2011-03-16 10:51:07

+0

嗨,試試這個鏈接,它將有處理(解析)json和XML的工作代碼服務器響應。 http://www.ibm.com/developerworks/xml/library/x-andbene1/謝謝。 – 2011-03-16 11:15:44

回答

4

下面是Android的活動從Web服務讀取和解析JSON對象的代碼:

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