Java 在 Volley 上 GET 时如何发送请求标头为 "Content-Type":"application/json"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43486027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:55:24  来源:igfitidea点击:

How to send request Header is "Content-Type":"application/json" when GET on Volley

javaandroidandroid-volley

提问by Morton

I try to use GET on Volley , but i need send request to application/json.

我尝试在 Volley 上使用 GET,但我需要将请求发送到application/json.

I take a look for some answers , i try to use jsonBody, but it shows error:

我看看一些答案,我尝试使用jsonBody,但它显示错误:

null com.android.volley.ServerError

null com.android.volley.ServerError

Here is my code:

这是我的代码:

public class MainActivity extends AppCompatActivity {

    String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
    JSONObject jsonBody;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            //I try to use this for send Header is application/json
            jsonBody = new JSONObject("{\"type\":\"example\"}");
        } catch (JSONException ex) {
            ex.printStackTrace();
        }

        RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
                new Response.Listener<JSONObject>() {


                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("TAG", response.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        });


        mQueue.add(jsonObjectRequest);

    }


}

Is any one can teach me how to fix this , any help would be appreciated.

任何人都可以教我如何解决这个问题,任何帮助将不胜感激。

Here is my url: String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";

这是我的网址: String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";

采纳答案by Mukeshkumar S

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    Map<String, String> params = new HashMap<String, String>();                
    params.put("Content-Type", "application/json");
    return params; 
} 

Implementation in your's

在您的实施

public class MainActivity extends AppCompatActivity {

    String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("TAG", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("TAG", error.getMessage(), error);
                }
            }) { //no semicolon or coma
            @Override 
            public Map<String, String> getHeaders() throws AuthFailureError { 
                Map<String, String> params = new HashMap<String, String>();                
                params.put("Content-Type", "application/json");
                return params; 
            } 
        };
        mQueue.add(jsonObjectRequest);
    }
}

回答by Rajesh Nasit

Use String request instead of jsonrequest like this

像这样使用 String request 而不是 jsonrequest

            StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    System.out.println("LoginActivity -- onResponse --> " + response);

                    if (progressDialog != null) {

                        progressDialog.dismiss();

                    }

                    try {

                        JSONObject jsonObject = new JSONObject(response);

                    } catch (Exception e) {

                        CommonUtility.somethingWentWrongDialog(activity,
                                "LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));

                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    if (progressDialog != null) {

                        progressDialog.dismiss();

                    }

                    CommonUtility.somethingWentWrongDialog(activity,
                            "LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));

                }
            }) {

                @Override
                protected Map<String, String> getParams() {

                    Map<String, String> params = new HashMap<>();


                    System.out.println("LoginActivity -- LoginParams --> " + params.toString());

                    return params;

                }
            };

            loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            Volley.newRequestQueue(activity).add(loginMe);

回答by akash93

In general for setting a custom header you need to override getHeadersand set the custom header manually. However, volley handles content type headers differently and getHeadersway does not always work.

一般来说,要设置自定义标题,您需要getHeaders手动覆盖和设置自定义标题。但是,volley 以不同的getHeaders方式处理内容类型标头,并且方式并不总是有效。

So for your case you need to override getBodyContentType. So your code will look like

因此,对于您的情况,您需要覆盖getBodyContentType. 所以你的代码看起来像

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
   Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", error.getMessage(), error);
        }


    }){
         @Override
         public String getBodyContentType(){
              return "application/json";
         }
    };

回答by OneCricketeer

I try to use GET on Volley

我尝试在 Volley 上使用 GET

The docs for the method you are calling says this

您正在调用的方法的文档说明了这一点

Constructor which defaults to GET if jsonRequest is null, POST otherwise

如果 jsonRequest 为 null,则默认为 GET 的构造函数,否则POST

You can't GET with an HTTP JSON body. Maybe that's the error.

您无法使用 HTTP JSON 正文进行 GET。也许这就是错误。

//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");

That's not the header, so pass in null here to do GET

那不是标题,所以在这里传入 null 来做 GET

new JsonObjectRequest(url, null,

And towards the end of your request, override a method to request JSON

在您的请求结束时,覆盖请求 JSON 的方法

        ... 

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("TAG", error.getMessage(), error);
        }


    }) { // Notice no semi-colon here
        @Override 
        public Map<String, String> getHeaders() throws AuthFailureError { 
            Map<String, String> params = new HashMap<String, String>();                
            params.put("Content-Type", "application/json");
            return params; 
        } 
    };