2011-03-16 41 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