使用 JsonObjectRequest 和 GET 请求发送 JSON 正文 [英] Send JSON body with JsonObjectRequest And GET request

查看:73
本文介绍了使用 JsonObjectRequest 和 GET 请求发送 JSON 正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过 get 方法发送一个 json 代码.我尝试通过带有方法、url 和参数的 JsonObjectRequest 发送,响应为空且未发送 json.

I need to send a json code, via the get method. I tried to send through a JsonObjectRequest with the method, url and the parameters, the response was null and the json was not sent.

JSONObject request = new JSONObject();
try {
    request.put("CodigoInicial", "1");
    request.put("CodigoFinal", "2");
    ;
} catch (JSONException e) {
    e.printStackTrace();
}


// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
        Request.Method.GET, url2,request,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
              //  Log.d(TAG, response.toString() + " i am queen");

                try {
                    JSONArray jsonArray = response.getJSONArray("LinhasClientes");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject employee = jsonArray.getJSONObject(i);
                        int codigo = employee.getInt("Codigo");
                        String Nome = employee.getString("Nome");
                        String NumContrib = employee.getString("NumContrib");
                        //textView.append(Nome + ", " + String.valueOf(codigo) + ", " + NumContrib + "\n\n");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }




                Toast.makeText(getApplicationContext(),
                        response.toString()+"i am queen", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //VolleyLog.d(TAG, "Error: " + error.getMessage());
        Toast.makeText(getApplicationContext(),
                error.getMessage(), Toast.LENGTH_SHORT).show();
    }
}) {

    /**
     * Passing some request headers
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        headers.put("CodigoInicial","1");
        headers.put("C`enter code here`odigoFinal","2");
        return headers;
    }

};

// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);

推荐答案

问题是com.android.volley.toolbox.HttpClientStack.java中createHttpRequest方法的实现,只有请求方法为POST时才会添加body、PUT 或 PATCH.

The problem is the implementation of the createHttpRequest method in com.android.volley.toolbox.HttpClientStack.java which will add the body only if the request method is POST, PUT or PATCH.

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 */
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST: {
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                HttpPost postRequest = new HttpPost(request.getUrl());
                postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
                HttpEntity entity;
                entity = new ByteArrayEntity(postBody);
                postRequest.setEntity(entity);
                return postRequest;
            } else {
                return new HttpGet(request.getUrl());
            }
        }
        case Method.GET:
            return new HttpGet(request.getUrl());
        case Method.DELETE:
            return new HttpDelete(request.getUrl());
        case Method.POST: {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            setEntityIfNonEmptyBody(postRequest, request);
            return postRequest;
        }
        case Method.PUT: {
            HttpPut putRequest = new HttpPut(request.getUrl());
            putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            setEntityIfNonEmptyBody(putRequest, request);
            return putRequest;
        }
        case Method.HEAD:
            return new HttpHead(request.getUrl());
        case Method.OPTIONS:
            return new HttpOptions(request.getUrl());
        case Method.TRACE:
            return new HttpTrace(request.getUrl());
        case Method.PATCH: {
            HttpPatch patchRequest = new HttpPatch(request.getUrl());
            patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
            setEntityIfNonEmptyBody(patchRequest, request);
            return patchRequest;
        }
        default:
            throw new IllegalStateException("Unknown request method.");
    }
}

因此您必须使用自己的 HttpStack.java 实现或覆盖 HttpClientStack 类.

So you have to use your own implementation of HttpStack.java or you override HttpClientStack class.

首先你应该从

RequestQueue requestQueue = Volley.newRequestQueue(sContext);

    String userAgent = "volley/0";
    try {
        String packageName = getContext().getPackageName();
        PackageInfo info = getContext().getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {}
    HttpStack httpStack = new OwnHttpClientStack(AndroidHttpClient.newInstance(userAgent));
    RequestQueue requesQueue = Volley.newRequestQueue(sContext, httpStack);

并编写您自己的 HttpClientStack 实现,您可以在其中更改Method.POST:"的大小写;在方法 createHttpRequest() 中.您还必须创建一个像OwnHttpDelete"这样的对象.作为 HttpEntityEnclosureRequestBase 的扩展,使用 setEntityIfNonEmptyBody() 方法.

and write your own implementation of HttpClientStack where you change the case of "Method.POST:" in the method createHttpRequest(). You also have to create an Object like "OwnHttpDelete" as extention of HttpEntityEnclosingRequestBase to use the method setEntityIfNonEmptyBody().

public class OwnHttpClientStack extends com.android.volley.toolbox.HttpClientStack {
    private final static String HEADER_CONTENT_TYPE = "Content-Type";

    public OwnHttpClientStack(HttpClient client) {
        super(client);
    }

    @Override
    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
        addHeaders(httpRequest, additionalHeaders);
        addHeaders(httpRequest, request.getHeaders());
        onPrepareRequest(httpRequest);
        HttpParams httpParams = httpRequest.getParams();
        int timeoutMs = request.getTimeoutMs();
        // TODO: Reevaluate this connection timeout based on more wide-scale
        // data collection and possibly different for wifi vs. 3G.
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
        return mClient.execute(httpRequest);
    }

    private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) {
        for (String key : headers.keySet()) {
            httpRequest.setHeader(key, headers.get(key));
        }
    }

    static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError {
        switch (request.getMethod()) {
            case Request.Method.DEPRECATED_GET_OR_POST: {
                byte[] postBody = request.getPostBody();
                if (postBody != null) {
                    HttpPost postRequest = new HttpPost(request.getUrl());
                    postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
                    HttpEntity entity;
                    entity = new ByteArrayEntity(postBody);
                    postRequest.setEntity(entity);
                    return postRequest;
                } else {
                    return new HttpGet(request.getUrl());
                }
            }
            case Request.Method.GET:
                return new HttpGet(request.getUrl());
            case Request.Method.DELETE:
                OwnHttpDelete deleteRequest =  new OwnHttpDelete(request.getUrl());
                deleteRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
                setEntityIfNonEmptyBody(deleteRequest, request);
                return deleteRequest;
            case Request.Method.POST: {
                HttpPost postRequest = new HttpPost(request.getUrl());
                postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
                setEntityIfNonEmptyBody(postRequest, request);
                return postRequest;
            }
            case Request.Method.PUT: {
                HttpPut putRequest = new HttpPut(request.getUrl());
                putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
                setEntityIfNonEmptyBody(putRequest, request);
                return putRequest;
            }
            case Request.Method.HEAD:
                return new HttpHead(request.getUrl());
            case Request.Method.OPTIONS:
                return new HttpOptions(request.getUrl());
            case Request.Method.TRACE:
                return new HttpTrace(request.getUrl());
            case Request.Method.PATCH: {
                HttpPatch patchRequest = new HttpPatch(request.getUrl());
                patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
                setEntityIfNonEmptyBody(patchRequest, request);
                return patchRequest;
            }
            default:
                throw new IllegalStateException("Unknown request method.");
        }
    }

    private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
                                                Request<?> request) throws AuthFailureError {
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }

    private static class OwnHttpDelete extends HttpPost {
        public static final String METHOD_NAME = "DELETE";

        public OwnHttpDelete() {
            super();
        }

        public OwnHttpDelete(URI uri) {
            super(uri);
        }

        public OwnHttpDelete(String uri) {
            super(uri);
        }

        public String getMethod() {
            return METHOD_NAME;
        }
    }
}

这篇关于使用 JsonObjectRequest 和 GET 请求发送 JSON 正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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