【问题标题】:android Volley delete method, why will send empty parametersandroid Volley删除方法,为什么会发送空参数
【发布时间】:2013-09-27 12:24:39
【问题描述】:

我使用 android volley 库!我有些不明白使用 json 和 DELETE 方法从服务器发送请求的问题。请求成功连接到服务器,但发送的参数服务器将接收为空。但是标头请求工作正常!请帮我!

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();
        }
    };
}

【问题讨论】:

    标签: android json httprequest


    【解决方案1】:

    这个issue已经解决了

    你可以重写 HurlStack 类

    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");
    

    使用 DELETE 方法的请求将像 POST 一样简单,例如

        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);
    

    只能解决android os 5.0设备问题 android os 4.2.2 设备出现新问题 它会抛出以下异常

    java.net.ProtocolException: DELETE does not support writing
    

    重写 Volley.newRequestQueue(Context context, HttpStack stack) 方法可以解决这个问题

        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);
      }   
    }
    

    它对我有用,希望对你也有用

    【讨论】:

      【解决方案2】:

      尝试使用 URL 传递参数,就像使用 GET 请求一样。为我工作:)
      代码示例(未测试):

      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
      

      【讨论】:

      • 这不是最好的事情,但绝对可以解决这个问题。
      猜你喜欢
      • 2014-09-15
      • 2021-03-07
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多