【问题标题】:How to send multiple json objects's data to server in android?如何将多个json对象的数据发送到android中的服务器?
【发布时间】:2015-06-23 19:18:10
【问题描述】:

如何向服务器发送多个 json 值。

    public class UserVO {
    private String userId;
    private String firstName;
    private String lastName;   
    private String mobileNumber;
    private String stdCode;
    private String landlineNumber;
    private String countryCode;
    private String stateCode;
    private String zipcode;
    private String status;    
    private LoginVO loginVO;
    private AddressVO addressVO;
    private proofVO proofVO VO;
}

我是这样实现的。

next_Edit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new CreateUser().execute();

        }
    });

class CreateUser extends AsyncTask<String, String, String> {
    int success=0;
    JSONObject json;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ConsentActivity.this);
        pDialog.setMessage("Registering New User..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        SharedPreferences pref = getSharedPreferences("UserMgmt", Context.MODE_PRIVATE);

        String Firstname = pref.getString("FName", "");
        String Lastname = pref.getString("LName", "");
        String Userid = pref.getString("UserId", "");
        String Password = pref.getString("Password", "");
        String Repassword = pref.getString("RePassword", "");

        String Idproof_typ=pref.getString("IdType","");
        String Idproof_number=pref.getString("IdNumber","");
        String Dob=pref.getString("DOB","");
        String Gender=pref.getString("Gender","");
        String Email=pref.getString("Email","");
        String Mobile_number=pref.getString("Mobile","");
        String Country_code=pref.getString("CountryCode","");
        String Landline=pref.getString("LandLine","");

        String Country=pref.getString("Country","");
        String State=pref.getString("State","");
        String Address=pref.getString("Address","");
        String Pincod=pref.getString("Pincode","");

        boolean Tc_chk_state = pref.getBoolean("ChkBoxTC", true);
        String status_tc_chk=String.valueOf(Tc_chk_state);
        String status_tc=status_tc_chk.substring(0,1);

        boolean Consent_chk_state = pref.getBoolean("ChkBoxConsent", true);
        String status_con_chk=String.valueOf(Tc_chk_state);
        String status_con=status_con_chk.substring(0,1);

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("userId", Userid));
        params.add(new BasicNameValuePair("firstName", Firstname));
        params.add(new BasicNameValuePair("lastName", Lastname));
        params.add(new BasicNameValuePair("identityType", Idproof_typ));
        params.add(new BasicNameValuePair("identityNumber", Idproof_number));
        params.add(new BasicNameValuePair("dob", Dob));
        params.add(new BasicNameValuePair("gender", Gender));
        params.add(new BasicNameValuePair("emailId", Email));
        params.add(new BasicNameValuePair("mobileNumber", Mobile_number));
        params.add(new BasicNameValuePair("stdCode", Country_code));
        params.add(new BasicNameValuePair("landlineNumber", Landline));
        params.add(new BasicNameValuePair("countryCode", Country));
        params.add(new BasicNameValuePair("stateCode", State));
        params.add(new BasicNameValuePair("zipcode", Pincod));
        params.add(new BasicNameValuePair("status", status_tc));
        params.add(new BasicNameValuePair("password", Password));
        params.add(new BasicNameValuePair("address", Address));


       /*json = jsonParser.makeHttpRequest(url_new_user,
                "POST",params);*/
              //  Log.d("Create Response", json.toString());

        JSONArray jsonArray = new JSONArray();
        final  JSONObject json = new JSONObject();
        final JSONObject login = new JSONObject();
        final JSONObject address = new JSONObject();
        final JSONObject identity = new JSONObject();
        HttpResponse response;
        HttpClient client = new DefaultHttpClient();
        HttpContext httpContext = new BasicHttpContext();
        HttpPost post = new HttpPost("http://191.121.1.145:8080/medicine/services/users/createUser");
        post.setHeader("Content-type", "application/json");
        try {

            Log.e("userId",Userid);
            Log.e("firstName",Firstname);
            Log.e("lastName",Lastname);
            Log.e("emailId",Email);
            Log.e("password",Password);
            Log.e("newPassword",Repassword);
            Log.e("status",status_tc);


            json.put("userId", Userid);
            json.put("firstName", Firstname);
            json.put("lastName", Lastname);
            //json.put("identityType",Idproof_typ);
            //json.put("identityNumber",Idproof_number);
            json.put("dob",Dob);
            json.put("gender",Gender);
            json.put("emailId", Email);
            json.put("mobileNumber",Mobile_number);
            json.put("stdCode",Country_code);
            json.put("landlineNumber",Landline);
            json.put("countryCode",Country);
            json.put("stateCode",State);
            json.put("zipcode",Pincod);
            json.put("status",status_tc);
            //json.put("password",Password);
           // json.put("address",Address);
            jsonArray.put(json);
            try{
                login.put("password",Password);
                jsonArray.put(login);
            }catch(Exception exception){
                exception.printStackTrace();
            }


            try{
                address.put("address",Address);
                jsonArray.put(address);
            }catch(Exception exception){
                exception.printStackTrace();
            }


            try{
                identity.put("identityType",Idproof_typ);
                identity.put("identityNumber",Idproof_number);
                jsonArray.put(identity);
            }catch(Exception exception){
                exception.printStackTrace();
            }

            StringEntity se = new StringEntity( jsonArray.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 201){
                Log.e("Responce","OK");
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            //Toast.makeText(getApplicationContext(), "establishment with server failed", Toast.LENGTH_LONG).show();
            // createDialog("Error", "Cannot Estabilish Connection");
        }
        /*try {
            success = json.getInt(TAG_SUCCESS);


        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }*/



        return null;
    }

   protected void onProgressUpdate(Integer... progress) {

   }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();

            /* try {
                int success = json.getInt(TAG_SUCCESS);*/

                if (success == 1) {
                // successfully created a user
                Intent i = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(i);
                // closing this screen
                finish();
               } /*else {
                // failed to create user
              //  Log.d("failed to create user", json.toString());

                 }*/
        /*} catch (JSONException e) {
            e.printStackTrace();
        }*/

    }

}

这里 upto status 是直接值,在 userVO 里面还有另外三个 VO,比如 loginVO,AddressVO,proofVO。

在这些 VO 类中,有 5 个值。

现在如何使用 POST 方法将这些详细信息发送到服务器。我完全糊涂了。

你能给出明确的解决方案吗?

【问题讨论】:

  • 这些变量中没有一个是恒定的,或者它们在运行时会发生变化。
  • 我从编辑文本中获取这些值
  • 你能告诉我什么是最好的发送方式吗...用一些示例代码
  • 我发布了答案。检查它是否适合您。
  • 我实现了一些代码......它是正确的

标签: android json http-post server


【解决方案1】:

您可以使用 HTTP post 方法发送数据。

 public void postData(){  
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");  

    try {
        // Add your data
        List nameValuePairs = new ArrayList(1);

        // Your user variable which are directly send from here 
        nameValuePairs.add(new BasicNameValuePair("data1", "dataValue"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);

        int current = 0;

        while((current = bis.read()) != -1){
            baf.append((byte)current);
        }  

        /* Convert the Bytes read to a String. */
        text = new String(baf.toByteArray());
        txtvw.setText(text);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

你可以在这个链接https://fahmirahman.wordpress.com/2011/04/26/the-simplest-way-to-post-parameters-between-android-and-php/找到完整的教程

另外我推荐你使用非常简单的ION网络库。

https://github.com/koush/ion

你会找到你需要的所有信息。

【讨论】:

  • 感谢代码主...真的我感到很高兴...对于这个示例...感谢分配您的帮助...我已经实现了一些代码...你可以检查一下?非常感谢@Code Lord
  • @androidstar 不要同时使用名称值对和 json 帖子。只使用其中之一。尝试使用非常简单的离子库。它将把你上面的所有代码减少到 10 行。
  • ok @Code Lord...我将删除 NameValue 对...我会尝试使用 json 库...
【解决方案2】:

要将对象转换为 JSON,可以使用GSON library

Gson 是一个 Java 库,可用于将 Java 对象转换为 他们的 JSON 表示。它还可以用于转换 JSON 字符串转换为等效的 Java 对象。

步骤:

  1. 只需使用 GSON 库即可将您的对象转换为 JSON
  2. 将 JSON 转换为字符串
  3. 使用 HTTPPost 发布字符串

【讨论】:

    【解决方案3】:

    您必须将其作为 HTTP 发送。 HTTP 消息以文本形式发送。因此,您需要创建 JSON 对象的字符串表示形式。 类似的东西

    {
      UserVO: {
        userId: "",
        firstName: ""
      }
    }
    

    【讨论】:

      【解决方案4】:

      您尝试过名称值对吗?如果不尝试使用我的以下代码

      HttpClient client = new DefaultHttpClient();
              HttpPost post = new HttpPost("url");
          List<NameValuePair> value = new ArrayList<NameValuePair>();
          value.add(new BasicNameValuePair("userid", userId)); //the userid which is inside the  "" is server variable
      
          //Form as like above for all variable then use below line of code to get response
          post.setEntity(new UrlEncodedFormEntity(name));
      
                      HttpResponse response = client.execute(post);
                      BufferedReader rd = new BufferedReader(new InputStreamReader(
                              response.getEntity().getContent()));
                      String line = "";
                      StringBuilder sb = new StringBuilder();
                      while ((line = rd.readLine()) != null) {
                          sb.append(line + "\n");
                      }
                      String result = sb.toString();
      

      如果您需要任何帮助,请发表评论

      【讨论】:

      • 我已经尝试了一些代码...你能看看那个代码...是的我实现了名称值对...
      • name 值对就够了 不要使用json.put("userId", Userid);(去掉这行代码再尝试执行)
      • 在我的 UserVo 类中的代码中,还有另外三个 VO 类,例如 addressVO、proofVO、LoginVO,所以在这些类中还有 5 个值...所以我可以使用 NameValue 对发送这些值...如果是的话...根据我的代码给出一些代码...
      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 2015-04-05
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多