2014-11-01 102 views
-6

如果有人可以解释这些代码行是什么意思。将非常感激。由于这段代码做了什么,我需要了解

JSONObject req = new JSONObject(); 
boolean flag = false; 
try { 
    req.put("name", p_name.getText().toString()); 
    String res = HttpClient.SendHttpPost(Constants.NAME, req.toString()); 
    if(res != null){ 
     JSONObject json = new JSONObject(res); 
     if(json.getBoolean("status")){ 
      flag = true; 
      String id = json.getString("userid"); 
      app.getUserinfo().SetUserInfo(id); 
     } 
    } 
+5

哪一部分,如果这个代码不清晰? – Pshemo 2014-11-01 15:19:44

+2

你从哪里找到这段代码,因为它没有记录? – 2014-11-01 15:25:52

回答

1
//creating a json object 
JSONObject req = new JSONObject(); 
boolean flag = false; 
try { 
    //save the string from p_name to the json 
    req.put("name", p_name.getText().toString()); 
    //send the json string to the server 
    String res = HttpClient.SendHttpPost(Constants.NAME, req.toString()); 
    if(res != null){ 
     //if you get the response correctly, convert the response to a json object (or we call it "parse") 
     JSONObject json = new JSONObject(res); 
     //if the "status" in the json represents true, make "flag" true and then set the user id 
     if(json.getBoolean("status")){ 
      flag = true; 
      String id = json.getString("userid"); 
      app.getUserinfo().SetUserInfo(id);   
     } 
    } 
3

简单

此代码发送一个名称到远程API,它返回一个用户ID和成功的状态(大概只有名称由远程服务中找到)。用户标识然后存储在我们的本地应用程序中。


逐行解释

  1. 首先,我们创建一个名为req JSON对象。

    JSONObject req = new JSONObject(); 
    
  2. 然后我们存储在p_name字符串保存到的req

    boolean flag = false; 
    try { 
        req.put("name", p_name.getText().toString()); 
    
  3. name场那么我们HTTP POST JSON对象的字符串序列化到我们的服务器。 res将以字符串形式存储我们收到的回复。

    String res = HttpClient.SendHttpPost(Constants.NAME, req.toString()); 
    
  4. POST返回后,我们检查响应是否为空。

    if(res != null){ 
    
  5. 如果它不为空,我们把响应转换成一个JSON对象(大概是这个服务器会返回有效的JSON。

    JSONObject json = new JSONObject(res); 
    
  6. 我们检查,看看是否在我们的响应对象领域status是真的。(响应会是什么样{"status":"true","userid":"a-user-id"}如果你看了原始服务器输出。)

    if(json.getBoolean("status")){ 
    
  7. 如果是的话,W e设置标志为true,从响应对象获取userid字段,并将我们应用程序的用户标识设置为从服务器返回的标识。

    flag = true; 
        String id = json.getString("userid"); 
        app.getUserinfo().SetUserInfo(id);