使用Volley android将发布数据发送到服务器

时间:2022-10-22 22:57:52

I am trying to send some data to the server using the Volley library.

我正在尝试使用Volley库将一些数据发送到服务器。

   private void registerUser(final String email, final String username,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    pDialog.setMessage("Registering ...");


    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());


            try {
                JSONObject jObj = new JSONObject(response);
              //  String status = jObj.getString("status");

                    // User successfully stored in MySQL
                    // Now store the user in sqlite

                    String name = jObj.getString("username");
                    String email = jObj.getString("email");
                    String password = jObj.getString("password");
                   // String created_at = user
                            //.getString("created_at");

                    // Inserting row in users table
                   // db.addUser(name, email);

                    // Launch login activity
                    Intent intent = new Intent(
                            RegisterActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();


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

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();


            params.put("email", email);
            params.put("username", username);
            params.put("password", password);

            return params;
        }

Unfortunately no json is sent and I get nothing back. Here is a sample of my logcat output. After sending a request successfully to the server, I want to get response with success/fail.

不幸的是没有发送json,我什么都没收到。这是我的logcat输出的示例。在成功向服务器发送请求后,我想获得成功/失败的响应。

Register Response: ---- YOUR DATA ----
username=xxx&email=xxx%40gmail.com&password=xxxx&-------------------
05-05 14:56:55.002    2558-2558/app.victory.walking.thewalkingviktory   
W/System.err﹕ org.json.JSONException: Value ---- of type java.lang.String   
cannot be converted to JSONObject
05-05 14:56:55.002    2558-2558/app.victory.walking.thewalkingviktory   
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
05-05 14:56:55.002    2558-2558/app.victory.walking.thewalkingviktory   
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
05-05 14:56:55.002    2558-2558/app.victory.walking.thewalkingviktory   
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)

Any help please? Thanx.

有什么帮助吗?感谢名单。

5 个解决方案

#1


 private void postUsingVolley() {
    String tag_json_obj = "json_obj_req";

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("posting...");
    pDialog.show();

    final String mVendorId = DeviceDetails.getInstance(mContext).getVendor_id();
    String mUserId = UserModel.getInstance(mContext).getUser_id();

    final HashMap<String, String> postParams = new HashMap<String, String>();
    sendFeedbackParams.put("key1", value1);
    sendFeedbackParams.put("key2", value2);
    sendFeedbackParams.put("key3", value3);

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            ApplicationData.POST_URL, new JSONObject(postParams),
            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    //Log.d("TAG", response.toString());
                    try {
                        //Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show();
                        Toast.makeText(mContext, "Thank you for your post", Toast.LENGTH_LONG).show();

                        if (response.getBoolean("status")) {
                            pDialog.dismiss();
                            finish();
                        }
                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }
                    pDialog.dismiss();
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("TAG", "Error: " + error.getMessage());
            pDialog.dismiss();
            if (isNetworkProblem(error)) {
                Toast.makeText(mContext, "Internet Problem", Toast.LENGTH_SHORT).show();

            }
        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return getRequestHeaders();
        }
    };

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(8000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

Use Volley like this,... It is working for me.

像这样使用Volley,......这对我有用。

#2


First of all you are not sending json to your server. You are sending parametrized url with post method and getting json text as response.

首先,您不是将json发送到您的服务器。您正在使用post方法发送参数化URL并获取json文本作为响应。

I think the problem is the response from the server which is supposedly json. But from your log, this text "---- YOUR DATA ----" which you get from Log.d(TAG, "Register Response: " + response.toString()); is not at all json formatted . So you need to modify your server to respond in correct json format.

我认为问题是来自服务器的响应,据说是json。但是从你的日志中,你可以从Log.d获得这个文本“----你的数据----”(TAG,“注册响应:”+ response.toString());根本不是json格式化的。因此,您需要修改服务器以响应正确的json格式。

#3


This is the solution. I had to use the JsonObjectRequest class and not the StringRequest on. What JsonRequest does is that it converts your HashMap key-value pairs into a JSON Format.

这是解决方案。我不得不使用JsonObjectRequest类而不是StringRequest。 JsonRequest做的是它将您的HashMap键值对转换为JSON格式。

    private void registerUser(String email_address,String username, String 
    password) {
    String tag_json_obj = "json_obj_req";

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("posting...");
    pDialog.show();

    final String mVendorId = 
     DeviceDetails.getInstance(mContext).getVendor_id();
     String mUserId = UserModel.getInstance(mContext).getUser_id();
    String location = getResources().getConfiguration().locale.getCountry();
    final HashMap<String, String> postParams = new HashMap<String, String>  
    ();
    postParams.put("username", username);
    postParams.put("email", email_address);
    postParams.put("password", password);
    postParams.put("location", location);



    Response.Listener<JSONObject>  listener;
    Response.ErrorListener errorListener;
    final JSONObject jsonObject = new JSONObject(postParams);

    JsonObjectRequest jsonObjReq = new 
    JsonObjectRequest(AppConfig.URL_REGISTER, jsonObject,
            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    //Log.d("TAG", response.toString());
                    try {
                        Toast.makeText(getApplicationContext(), 
       response.getString("message"), Toast.LENGTH_LONG).show();
                        // Toast.makeText(getApplicationContext(), "Thank 
       you for your post", Toast.LENGTH_LONG).show();

                        if (response.getString("status").equals("success")){


                            session.setLogin(true);


                            pDialog.dismiss();
                           Intent i = new 
        Intent(RegisterActivity.this,Welcome.class);
                           startActivity(i);

                            finish();
                        }
                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }
                    pDialog.dismiss();
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("TAG", "Error: " + error.getMessage());
            pDialog.dismiss();

        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }


    };


    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);



  }

#4


JSon post

public void makePostUsingVolley() 
{
  session = new SessionManager(getActivity().getApplicationContext());
  session.checkLogin();
  HashMap<String, String> user = session.getUserDetails();

  final String  token = user.get(SessionManager.KEY_NAME);

  //Toast.makeText(getActivity().getApplicationContext(),name, Toast.LENGTH_SHORT).show();

  final Map<String, String> params = new HashMap<String, String>();
  //params.put("Employees",name);
  String tag_json_obj = "json_obj_req";
  String url = "enter your url";

  final ProgressDialog pDialog = new ProgressDialog(getApplicationContext());
  pDialog.setMessage("Loading...");
  pDialog.show();

 StringRequest req = new StringRequest(Request.Method.GET,url,
          new Response.Listener<String>() {
              // final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
              //"http://emservices.azurewebsites.net/Employee.asmx/CheckUserGet", new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(String response) {

                  JSONObject json;
                     // Toast.makeText(getActivity().getApplicationContext(),"dfgghfhfgjhgjghjuhj", Toast.LENGTH_SHORT).show();



                    //Toast.makeText(getActivity().getApplicationContext(),obb.length(), Toast.LENGTH_SHORT).show();



                  // JSONObject data=obj.getJSONObject("Employee_Name");
                  ObjectOutput out = null;
                  try {

                      json = new JSONObject(response);

                  } catch (IOException e) {
                      e.printStackTrace();
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }




                  pDialog.hide();
                  // Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_SHORT).show();
                  Log.d("", response);


              }
          }, new Response.ErrorListener() {

      @Override
      public void onErrorResponse(VolleyError error) {
          VolleyLog.d("", "Error: " + error.getMessage());
          Toast.makeText(getActivity().getApplicationContext(),
                  error.getMessage(), Toast.LENGTH_SHORT).show();
          pDialog.hide();
          // hide the progress dialog

      }
  }) {
     @Override
       protected Map<String, String> getParams() {
     Map<String, String> params = new HashMap<String, String>();
     params.put("username",name);
     params.put("password",password);

     return params;
 }

  };

  // Adding request to request queue
  AppController.getInstance().addToRequestQueue(req, tag_json_obj);
}

#5


requestQueue= Volley.newRequestQueue(MainActivity.this);
StringRequest request=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
        Log.d("response",response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
}){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", name.getText().toString().trim());
            jsonObject.put("email", email.getText().toString().trim());
            jsonObject.put("phone", phone.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("message", jsonObject.toString());

        return params;
    }
    };
requestQueue.add(request);

[["deep","dee@gmail.com","8888999999"]]

#1


 private void postUsingVolley() {
    String tag_json_obj = "json_obj_req";

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("posting...");
    pDialog.show();

    final String mVendorId = DeviceDetails.getInstance(mContext).getVendor_id();
    String mUserId = UserModel.getInstance(mContext).getUser_id();

    final HashMap<String, String> postParams = new HashMap<String, String>();
    sendFeedbackParams.put("key1", value1);
    sendFeedbackParams.put("key2", value2);
    sendFeedbackParams.put("key3", value3);

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            ApplicationData.POST_URL, new JSONObject(postParams),
            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    //Log.d("TAG", response.toString());
                    try {
                        //Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show();
                        Toast.makeText(mContext, "Thank you for your post", Toast.LENGTH_LONG).show();

                        if (response.getBoolean("status")) {
                            pDialog.dismiss();
                            finish();
                        }
                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }
                    pDialog.dismiss();
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("TAG", "Error: " + error.getMessage());
            pDialog.dismiss();
            if (isNetworkProblem(error)) {
                Toast.makeText(mContext, "Internet Problem", Toast.LENGTH_SHORT).show();

            }
        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return getRequestHeaders();
        }
    };

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(8000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

Use Volley like this,... It is working for me.

像这样使用Volley,......这对我有用。

#2


First of all you are not sending json to your server. You are sending parametrized url with post method and getting json text as response.

首先,您不是将json发送到您的服务器。您正在使用post方法发送参数化URL并获取json文本作为响应。

I think the problem is the response from the server which is supposedly json. But from your log, this text "---- YOUR DATA ----" which you get from Log.d(TAG, "Register Response: " + response.toString()); is not at all json formatted . So you need to modify your server to respond in correct json format.

我认为问题是来自服务器的响应,据说是json。但是从你的日志中,你可以从Log.d获得这个文本“----你的数据----”(TAG,“注册响应:”+ response.toString());根本不是json格式化的。因此,您需要修改服务器以响应正确的json格式。

#3


This is the solution. I had to use the JsonObjectRequest class and not the StringRequest on. What JsonRequest does is that it converts your HashMap key-value pairs into a JSON Format.

这是解决方案。我不得不使用JsonObjectRequest类而不是StringRequest。 JsonRequest做的是它将您的HashMap键值对转换为JSON格式。

    private void registerUser(String email_address,String username, String 
    password) {
    String tag_json_obj = "json_obj_req";

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("posting...");
    pDialog.show();

    final String mVendorId = 
     DeviceDetails.getInstance(mContext).getVendor_id();
     String mUserId = UserModel.getInstance(mContext).getUser_id();
    String location = getResources().getConfiguration().locale.getCountry();
    final HashMap<String, String> postParams = new HashMap<String, String>  
    ();
    postParams.put("username", username);
    postParams.put("email", email_address);
    postParams.put("password", password);
    postParams.put("location", location);



    Response.Listener<JSONObject>  listener;
    Response.ErrorListener errorListener;
    final JSONObject jsonObject = new JSONObject(postParams);

    JsonObjectRequest jsonObjReq = new 
    JsonObjectRequest(AppConfig.URL_REGISTER, jsonObject,
            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    //Log.d("TAG", response.toString());
                    try {
                        Toast.makeText(getApplicationContext(), 
       response.getString("message"), Toast.LENGTH_LONG).show();
                        // Toast.makeText(getApplicationContext(), "Thank 
       you for your post", Toast.LENGTH_LONG).show();

                        if (response.getString("status").equals("success")){


                            session.setLogin(true);


                            pDialog.dismiss();
                           Intent i = new 
        Intent(RegisterActivity.this,Welcome.class);
                           startActivity(i);

                            finish();
                        }
                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }
                    pDialog.dismiss();
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("TAG", "Error: " + error.getMessage());
            pDialog.dismiss();

        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }


    };


    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);



  }

#4


JSon post

public void makePostUsingVolley() 
{
  session = new SessionManager(getActivity().getApplicationContext());
  session.checkLogin();
  HashMap<String, String> user = session.getUserDetails();

  final String  token = user.get(SessionManager.KEY_NAME);

  //Toast.makeText(getActivity().getApplicationContext(),name, Toast.LENGTH_SHORT).show();

  final Map<String, String> params = new HashMap<String, String>();
  //params.put("Employees",name);
  String tag_json_obj = "json_obj_req";
  String url = "enter your url";

  final ProgressDialog pDialog = new ProgressDialog(getApplicationContext());
  pDialog.setMessage("Loading...");
  pDialog.show();

 StringRequest req = new StringRequest(Request.Method.GET,url,
          new Response.Listener<String>() {
              // final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
              //"http://emservices.azurewebsites.net/Employee.asmx/CheckUserGet", new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(String response) {

                  JSONObject json;
                     // Toast.makeText(getActivity().getApplicationContext(),"dfgghfhfgjhgjghjuhj", Toast.LENGTH_SHORT).show();



                    //Toast.makeText(getActivity().getApplicationContext(),obb.length(), Toast.LENGTH_SHORT).show();



                  // JSONObject data=obj.getJSONObject("Employee_Name");
                  ObjectOutput out = null;
                  try {

                      json = new JSONObject(response);

                  } catch (IOException e) {
                      e.printStackTrace();
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }




                  pDialog.hide();
                  // Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_SHORT).show();
                  Log.d("", response);


              }
          }, new Response.ErrorListener() {

      @Override
      public void onErrorResponse(VolleyError error) {
          VolleyLog.d("", "Error: " + error.getMessage());
          Toast.makeText(getActivity().getApplicationContext(),
                  error.getMessage(), Toast.LENGTH_SHORT).show();
          pDialog.hide();
          // hide the progress dialog

      }
  }) {
     @Override
       protected Map<String, String> getParams() {
     Map<String, String> params = new HashMap<String, String>();
     params.put("username",name);
     params.put("password",password);

     return params;
 }

  };

  // Adding request to request queue
  AppController.getInstance().addToRequestQueue(req, tag_json_obj);
}

#5


requestQueue= Volley.newRequestQueue(MainActivity.this);
StringRequest request=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
        Log.d("response",response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
}){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", name.getText().toString().trim());
            jsonObject.put("email", email.getText().toString().trim());
            jsonObject.put("phone", phone.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("message", jsonObject.toString());

        return params;
    }
    };
requestQueue.add(request);

[["deep","dee@gmail.com","8888999999"]]