我在Android项目中使用Volley将其连接到服务器。
我需要使用post
方法将数据发送到网址并获得响应,但是凌空不会传递我的数据。
这是我的代码:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jres=new JSONObject();
jres.opt(response);
if(jres.getString("value").toLowerCase()=="true"){
ConfirmMob=txtMob.getText().toString();
SubmitMob();
}
else{
AlertDialog.Builder dialog=new AlertDialog.Builder(App.getContext());
dialog.setMessage(R.string.IncorrectMob);
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
loading.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("IsMobValid - " + error.networkResponse, "Error: " + error.getMessage());
error.printStackTrace();
error.networkResponse
loading.hide();
}
}){
@Override
protected Map<String,String> getParams()throws AuthFailureError{
Map<String,String> params = new HashMap<String, String>();
params.put("x", "IsMobValid");
params.put("Mob", txtMob.getText().toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
App.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
我该如何修复它? 有什么不对吗?
答案 0 :(得分:0)
我认为凌空是瑕疵!
在JsonObjectRequest
请求中根本没有传递参数。
在StringRequest
请求发送自定义头部时,听起来HTTPRequest不正常。因为我的服务器会导致500 Error
!
删除下面的代码,我的问题已解决。
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
答案 1 :(得分:0)
JSON请求都失败了,因为在服务器端,所有POST参数都是空的!我的带有Express的node.js服务器正在使用express.bodyparser(),它以前在本地运行得很好。 同样奇怪的是,标题工作正常。
经过大量搜索并在Volley用户组中寻求帮助后,我遇到了一个提示,要在内容类型标题上设置charset。因为没有它,bodysarser无法正确解析该参数。 因此,正确的内容类型标题应为:
应用/ JSON;字符集= UTF-8
和正确的内容类型标题设置在第25行:
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("param1", youParameter);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST,
"https://your.url/here",
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
verificationSuccess(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
verificationFailed(error);
}
}) {
@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("User-agent", "My useragent");
return headers;
}
};
MyApplication.getInstance().addToRequestQueue(myRequest, "tag");