Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android Volley delete method, why will send empty parameters

I work with android volley library! I have some don't understand problem with sending request with json and DELETE method from server. Request successfully connect to server but sended parameters server will receive is empty. But header request work normaly! Please help me!

public void deletePoint(String id) throws JSONException {
    dialog.show();
    queue = Volley.newRequestQueue(getActivity(), new ExtHttpClientStack(new SslHttpClient().getHttpClient()));
    String urlRequest = getUrl();
    JSONObject param = new JSONObject();
    param.put("id", id);
    JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.DELETE,
            urlRequest,
            param,
            deletePointRequestSuccessListener(),
            reqErrorListener()){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = super.getHeaders();
            if (headers == null || headers.equals(Collections.emptyMap())) {
                headers = new HashMap<String, String>();
            }
            if (ProgressFragment.this.headers != null) {
                headers.keySet().removeAll(ProgressFragment.this.headers.keySet());
                headers.putAll(ProgressFragment.this.headers);
            }
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };

    userRequest.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    dialog.show();
    queue.add(userRequest);
}

private Response.Listener<JSONObject> deletePointRequestSuccessListener() {
    return new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            dialog.hide();
            Gson gson = new Gson();
            Success resp = gson.fromJson(response.toString(), Success.class);
            if(resp.isSuccess()){
                Toast.makeText(getActivity(), getString(R.string.success), Toast.LENGTH_SHORT).show();
                try {
                    getGraphData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            dialog.hide();
        }
    };
}
like image 602
billy gates Avatar asked Sep 27 '13 12:09

billy gates


2 Answers

it's this issue that has been resolved

you can rewrite the HurlStack class

public class HurlStack implements HttpStack {
             break;
         case Method.DELETE:
             connection.setRequestMethod("DELETE");
             addBodyIfExists(connection, request); // here call addBodyIfExists method
             break;
         case Method.POST:
             connection.setRequestMethod("POST");

request with DELETE method will be easy as POST,for example

    mQueue = Volley.newRequestQueue(context);
StringRequest postRequest = new StringRequest(Request.Method.DELETE, HttpUtils.URL_MSG,
    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            if (mCallBack!=null) {
            mCallBack.success(response);
            }
        }
    },
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error) {
        if (mCallBack!=null) {
            mCallBack.fail(null);
        }
        }
    }
) {
    @Override
    protected Map<String, String> getParams()
    {
    return params;
    }

};

mQueue.add(postRequest);

that can only resolve android os 5.0 devices problem there has new problem on android os 4.2.2 device it will throw the following exception

java.net.ProtocolException: DELETE does not support writing

to rewrite Volley.newRequestQueue(Context context, HttpStack stack) method can resovle this problem

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    .
    .
    .


    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new OkHttpStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    .
    .
    .


    return queue;
}

OkHttpStack.java(okhttp-1.6.0.jar)

public class OkHttpStack extends HurlStack {
  private final OkHttpClient client;

  public OkHttpStack() {
    this(new OkHttpClient());
  }

  public OkHttpStack(OkHttpClient client) {
    if (client == null) {
      throw new NullPointerException("Client must not be null.");
    }
    this.client = client;
  }

  @Override protected HttpURLConnection createConnection(URL url) throws IOException {
    return client.open(url);
  }   
}

it works for me, hoping that work for you as well

like image 158
Mr235 Avatar answered Nov 04 '22 03:11

Mr235


Try to pass parameters with the URL as you would do with a GET request. Worked for me :)
Code sample (not tested):

url += "?";
for(String key : params.keyset()){
  url += URLEncode.encode(key,"UTF-8") +"="+ URLEncode.encode( params.get(key),"UTF-8") +"&";
}
url = url.substring(0, url.length()-1); // remove last '&' char
like image 20
ApollonDigital Avatar answered Nov 04 '22 02:11

ApollonDigital