Android的凌空删除方法,为什么会发空参数 [英] android Volley delete method, why will send empty parameters

查看:367
本文介绍了Android的凌空删除方法,为什么会发空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Android凌空库工作!我有一些不使用JSON发送请求理解问题,并从服务器上删除的方法。申请成功连接到服务器,但sended参数服务器将接收空。但头请求工作normaly!请帮帮我!

 公共无效deletePoint(字符串ID)抛出JSONException {
    dialog.show();
    队列= Volley.newRequestQueue(getActivity(),新ExtHttpClientStack(新SslHttpClient()getHttpClient())。);
    字符串的URLRequest =的getURL();
    JSONObject的参数=新的JSONObject();
    param.put(ID,身份证);
    JsonObjectRequest userRequest =新JsonObjectRequest(Request.Method.DELETE,
            的URLRequest,
            参数,
            deletePointRequestSuccessListener(),
            reqErrorListener()){
        @覆盖
        公共地图<字符串,字符串> getHeaders()抛出AuthFailureError {
            地图<字符串,字符串>标题= super.getHeaders();
            如果(头== NULL || headers.equals(Collections.emptyMap())){
                标题=新的HashMap<字符串,字符串>();
            }
            如果(ProgressFragment.this.headers!= NULL){
                。headers.keySet()的removeAll(ProgressFragment.this.headers.keySet());
                headers.putAll(ProgressFragment.this.headers);
            }
            headers.put(内容类型,应用/ JSON);
            返回头;
        }
    };    userRequest.setRetryPolicy(新DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));    dialog.show();
    queue.add(userRequest);
}私人Response.Listener<&JSONObject的GT; deletePointRequestSuccessListener(){
    返回新Response.Listener<&JSONObject的GT;(){
        @覆盖
        公共无效onResponse(JSONObject的响应){
            dialog.hide();
            GSON GSON =新GSON();
            成功RESP = gson.fromJson(response.toString(),Success.class);
            如果(resp.isSuccess()){
                Toast.makeText(getActivity(),的getString(R.string.success),Toast.LENGTH_SHORT).show();
                尝试{
                    getGraphData();
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }
            dialog.hide();
        }
    };
}


解决方案

这是这个的 问题已得到解决。

您可以重写HurlStack类

 公共类HurlStack实现HttpStack {
             打破;
         案例Method.DELETE:
             connection.setRequestMethod(删除);
             addBodyIfExists(连接请求); //这里调用addBodyIfExists方法
             打破;
         案例Method.POST:
             connection.setRequestMethod(POST);

使用DELETE方法请求会容易,因为POST,例如:

  = mqueue中Volley.newRequestQueue(背景);
StringRequest postRequest =新StringRequest(Request.Method.DELETE,HttpUtils.URL_MSG,
    新Response.Listener<串GT;()
    {
        @覆盖
        公共无效onResponse(字符串响应){
            如果(mCallBack!= NULL){
            mCallBack.success(响应);
            }
        }
    },
    新Response.ErrorListener()
    {
        @覆盖
        公共无效onErrorResponse(VolleyError错误){
        如果(mCallBack!= NULL){
            mCallBack.fail(NULL);
        }
        }
    }
){
    @覆盖
    保护地图<字符串,字符串> getParams()方法
    {
    返回PARAMS;
    }};mQueue.add(postRequest);

这只能解决Android操作系统5.0的设备问题
有对Android操作系统4.2.2设备新的问题
它会抛出以下异常

  java.net.ProtocolException:删除不支持写入

改写Volley.newRequestQueue(上下文的背景下,HttpStack栈)方法可以resovle这个问题。

 公共静态请求队列newRequestQueue(上下文的背景下,HttpStack堆栈){
    。
    。
    。
    如果(堆栈== NULL){
        如果(Build.VERSION.SDK_INT> = 9){
            堆栈=新OkHttpStack();
        }其他{
            //此前姜饼,HttpURLConnection类是不可靠的。
            //参见:http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            堆栈=新HttpClientStack(AndroidHttpClient.newInstance(的userAgent));
        }
    }    。
    。
    。
    返回队列中;
}

OkHttpStack.java(okhttp-1.6.0.jar)

 公共类OkHttpStack扩展HurlStack {
  私人最终OkHttpClient客户端;  公共OkHttpStack(){
    这(新OkHttpClient());
  }  公共OkHttpStack(OkHttpClient客户端){
    如果(客户端== NULL){
      抛出新的NullPointerException(客户端不能为空);
    }
    this.client =客户端;
  }  @覆盖保护HttpURLConnection类的createConnection(网址URL)抛出IOException
    返回client.open(URL);
  }
}

它为我工作,希望能为您的工作,以及

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

解决方案

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

这篇关于Android的凌空删除方法,为什么会发空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆