使用Post方法volley调用API时的BasicNetwork.performRequest

时间:2017-11-20 05:57:33

标签: android json

我有一个GridView类别,我想获得相应的子类别。我正在使用Volley POST方法来完成它。 API通过Postman正常工作,但在应用BasicNetwork.performRequest: Unexpected response code 403 for API中调用时会出错。

这就是我调用API的方式

StatusActivity.java

public void _loadAPI_POST() {
    Map<String, String> jsonPOST = new HashMap<>();
    jsonPOST.put("CategoryId", "3");
    _SEND(jsonPOST); // Check INTERNET is ON or NOT ?
}

 private void _SEND(Map<String, String> getPARAM) {
    try {
        String URL = "http://api.statuscollection.in/api/GetCategoryData";
        VolleyApiCAll volleyApiCAll = new VolleyApiCAll(StatusActivity.this);
        volleyApiCAll.Volley_POST(getPARAM, URL, new VolleyApiCAll.VolleyCallback() {
            @Override
            public void onSuccessResponse(String result) {
                try {
                    if(result.matches("VOLLEY_NETWORK_ERROR")) {
                        Toast.makeText(StatusActivity.this, "NETWORK PROBLEM", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        try {
                            System.out.println("RESULT"+result);
                            // GET JSON THROUGH result
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

}

VolleyApiCAll.java

Context context;

public VolleyApiCAll(Context context_) {
    context=context_;
}

public interface VolleyCallback
{
    void onSuccessResponse(String result);
}
public void Volley_GET(String url, final VolleyCallback callback)
{

    StringRequest strREQ = new StringRequest(Request.Method.GET, url, new Response.Listener < String > ()
    {
        @Override
        public void onResponse(String Response)
        {
            callback.onSuccessResponse(Response);
        }

    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError e)
        {
            callback.onSuccessResponse("VOLLEY_NETWORK_ERROR");
        }
    })
    {
        /**
         * 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");
           headers.put("Authentication", "5vLGpxfO4_FktAkPB0iM--FQh18USYEG7LWWUCbITpGioOZ16QRxe0JuoryqhMHArMcv-lBleaddcJPG3bsj3m94qOke3uq3mXDtvPUZHFkqm9_3Eub7MYlVCudtd8i_qxnFYQFVV8OTNfQ4w01vDjwBvJI2zVUXl8M-A9YfH09sPslbJKyZUBZBNcAqjSOzeIneaNVPH0WWcBP9xx_GvsvISNLWAM1KWlSia5Kb7Glj2ufmdZwl_XE5h1C_0guL5AkJniyLK1cCFjOXH7dgjJA6vjwgc0ol488TyWPWA19sOzsdPrnuzr724-BK3Z84");
           return headers;
       }


    };
    MySingleton.getInstance(context).addToRequestQueue(strREQ);
}
private HashMap<String, String> createBasicAuthHeader(String username, String password)
{
    HashMap<String, String> headerMap = new HashMap<String, String>();

    String credentials = username + ":" + password;
    String base64EncodedCredentials =
            Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    headerMap.put("Authorization", "Basic " + base64EncodedCredentials);

    return headerMap;
}
String BOUNDARY = "INTELLIJ_AMIYA";

public void Volley_POST(final Map<String, String> params, String url,final VolleyCallback callback)
{
    try
    {

        RequestQueue requestQueue = Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()

        {
            @Override
            public void onResponse(String response)
            {
                callback.onSuccessResponse(response);

            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                callback.onSuccessResponse("POST_ERROR");

            }
        })



        {

           /* public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();


                return headers;
            }*/
            /**
             * Passing some request headers
             * */


            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();

                params.put("Authentication", "5vLGpxfO4_FktAkPB0iM--FQh18USYEG7LWWUCbITpGioOZ16QRxe0JuoryqhMHArMcv-lBleaddcJPG3bsj3m94qOke3uq3mXDtvPUZHFkqm9_3Eub7MYlVCudtd8i_qxnFYQFVV8OTNfQ4w01vDjwBvJI2zVUXl8M-A9YfH09sPslbJKyZUBZBNcAqjSOzeIneaNVPH0WWcBP9xx_GvsvISNLWAM1KWlSia5Kb7Glj2ufmdZwl_XE5h1C_0guL5AkJniyLK1cCFjOXH7dgjJA6vjwgc0ol488TyWPWA19sOzsdPrnuzr724-BK3Z84");
                params.put("Content-Type", "multipart/form-data; boundary=" + BOUNDARY+"; charset=utf-8");
                return params;
            }

            @Override
            public String getBodyContentType() {
                return "multipart/form-data; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError
            {
                try
                {
                    String postBody = createPostBody(params);

                    return postBody == null ? null : postBody.getBytes("utf-8");
                }
                catch (NegativeArraySizeException n)
                {
                    n.printStackTrace();
                    return null;
                }
                catch (UnsupportedEncodingException uee)
                {

                    uee.printStackTrace();
                    return null;
                }
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response)
            {

                String responseString = "post_error";
                if (response != null)
                {
                    try
                    {
                        responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        MySingleton.getInstance(context).addToRequestQueue(stringRequest);
    }


    catch (NegativeArraySizeException n)
    {
        n.printStackTrace();
    }



}
private String createPostBody(Map<String, String> params) {
    StringBuilder sbPost = new StringBuilder();
    for (String key : params.keySet()) {
        if (params.get(key) != null) {
            sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
            sbPost.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n\r\n");
            sbPost.append(params.get(key));
        }
    }

    return sbPost.toString();
}

0 个答案:

没有答案