gpt4 book ai didi

java - 如何在 Volley 上发送请求 Header 是 "Content-Type":"application/json"

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:49 25 4
gpt4 key购买 nike

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

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

null com.android.volley.ServerError

这是我的代码:

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

}


}

有谁能教我如何解决这个问题,我们将不胜感激。

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

最佳答案

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

在你的实现

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

关于java - 如何在 Volley 上发送请求 Header 是 "Content-Type":"application/json",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43486027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com