put not working on android Volley org.json.JSONException: End of input at character 0 of

huangapple go评论66阅读模式
英文:

put not working on android Volley org.json.JSONException: End of input at character 0 of

问题

我在Postman中发送请求,它可以工作,但是Volley不起作用。我总是得到错误!我在StackOverflow上搜索了一下,发现在响应为空时,Volley会返回错误,但是我已经添加了`CustomJsonObjectRequest`,问题仍然存在。

**错误信息**

    Volley org.json.JSONException: 输入结束位于字符0处

**CustomJsonObjectRequest**

    public class CustomJsonObjectRequest extends JsonObjectRequest {
    
        public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
            super(method, url, jsonRequest, listener, errorListener);
        }
    
        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                if (response.data.length == 0) {
                    byte[] responseData = "{}".getBytes("UTF8");
                    response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return super.parseNetworkResponse(response);
        }
    }

**Volley请求**

    EcoElement ecoElement = ecoElementArrayList.get(position);
    
    Map<String, String> params = new HashMap<String, String>();
    
    params.put("Id", ecoElement.getId().toString());
    params.put("Checked", ecoElement.getChecked().toString());
    
    JSONObject ObjParams = new JSONObject(params);
    
    try {
        CustomJsonObjectRequest getRequest = new CustomJsonObjectRequest(Request.Method.PUT, "https://ourwebsite.sslbeta.de/api/gardenapi/updateecoelements", ObjParams,
                response -> {
                    Toast.makeText(getContext(), "" + response, Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                },
                error -> {
                    Toast.makeText(getContext(), "" + error.toString(), Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                }
        );
        RequestQueueSingleton.getInstance(getContext()).addToRequestQueue(getRequest);
    } catch (Exception e) {
        Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
    }
英文:

I sent request with postman its working, but volley doesn't work. I always get error! I searched stackoverflow volley returns error when response is empty but i added CustomJsonObjectRequest still the issue remains.

Error message

Volley org.json.JSONException: End of input at character 0 of

CustomJsonObjectRequest

public class CustomJsonObjectRequest extends JsonObjectRequest {

    public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener&lt;JSONObject&gt; listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    @Override
    protected Response&lt;JSONObject&gt; parseNetworkResponse(NetworkResponse response) {
        try {
            if (response.data.length == 0) {
                byte[] responseData = &quot;{}&quot;.getBytes(&quot;UTF8&quot;);
                response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return super.parseNetworkResponse(response);
    }
}

Volley request

EcoElement ecoElement = ecoElementArrayList.get(position);

                Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();

                params.put(&quot;Id&quot;, ecoElement.getId().toString());
                params.put(&quot;Checked&quot;, ecoElement.getChecked().toString());

                JSONObject ObjParams = new JSONObject(params);



                try {
                    CustomJsonObjectRequest getRequest = new CustomJsonObjectRequest(Request.Method.PUT, &quot;https://ourwebsite.sslbeta.de/api/gardenapi/updateecoelements&quot;, ObjParams,
                            response -&gt; {
                                Toast.makeText(getContext(), &quot;&quot;+response, Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                            },
                            error -&gt; {
                                Toast.makeText(getContext(), &quot;&quot;+error.toString(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                            }
                    );
                    RequestQueueSingleton.getInstance(getContext()).addToRequestQueue(getRequest);
                } catch (Exception e) {
                    Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
                }

put not working on android Volley org.json.JSONException: End of input at character 0 of

答案1

得分: 0

以下是翻译好的部分:

这是解决方案,只需创建此方法并传递您的值。

private void CustomJsonObjectRequest() {

    String tag_string_req = "req_details";

    StringRequest strReq = new StringRequest(Request.Method.POST, <API URL>, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            getPerspective().showErrorLogs(TAG, "Response Invest : " + response);

            try {
                
                // 在这里解析您的响应
                
                
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Id", <ID VALUE HERE>);
            params.put("Checked", <TRUE or FALSE>);
            return params;
        }
    };

    strReq.setRetryPolicy(new RetryPolicy() {

        @Override
        public void retry(VolleyError arg0) throws VolleyError {
        }

        @Override
        public int getCurrentTimeout() {
            return 0;
        }

        @Override
        public int getCurrentRetryCount() {
            return 0;
        }
    });
    strReq.setShouldCache(false);
    addToRequestQueue(strReq, tag_string_req);
}

ID和Checked都必须具有String类型。并在MainActivity中创建以下方法:

private RequestQueue mRequestQueue;

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}
英文:

Here is the solution, just create this method and pass your value.

private void CustomJsonObjectRequest() {
String tag_string_req = &quot;req__details&quot;;
StringRequest strReq = new StringRequest(Request.Method.POST, &lt;API URL&gt;, new Response.Listener&lt;String&gt;() {
@Override
public void onResponse(String response) {
getPerspective().showErrorLogs(TAG, &quot;Response Invest : &quot; + response);
try {
// Parse your response here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map&lt;String, String&gt; getParams() {
Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
params.put(&quot;Id&quot;, &lt;ID VALUE HERE&gt;);
params.put(&quot;Checked&quot;, &lt;TRUE or FALSE&gt;);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
@Override
public void retry(VolleyError arg0) throws VolleyError {
}
@Override
public int getCurrentTimeout() {
return 0;
}
@Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
addToRequestQueue(strReq, tag_string_req);
}

Both ID and Checked must have String type.And create below methods in MainActivity:

 private RequestQueue mRequestQueue;
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public &lt;T&gt; void addToRequestQueue(Request&lt;T&gt; req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public &lt;T&gt; void addToRequestQueue(Request&lt;T&gt; req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

答案2

得分: 0

Finally i was able to fix the issues after hours of searching. There were two reasons to this, first is that api was returning null/empty so CustomJsonObjectRequest fixed that, and then another issue is that i forgot to add authentication headers. that was a silly mistake i know!

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json");
    headers.put("Authorization", "Bearer " + access_token);
    return headers;
}
};
英文:

Finally i was able to fix the issues after hours of searching. There were two reasons to this, first is that api was returning null/empty so CustomJsonObjectRequest fixed that, and then another issue is that i forgot to add authentication headers. that was a silly mistake i know!

        @Override
public Map&lt;String, String&gt; getHeaders() throws AuthFailureError {
HashMap&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;();
headers.put(&quot;Content-Type&quot;, &quot;application/json&quot;);
headers.put(&quot;Authorization&quot;, &quot;Bearer &quot;+access_token);
return headers;
}
};

huangapple
  • 本文由 发表于 2020年10月8日 20:14:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64262320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定