![](/img/trans.png)
[英]How to pass String value from a app to php web service using android volley
[英]How to post json with volley to php web service
我正在尝试通过齐射将Json发布到我的静态API,但是它不起作用。 到目前为止,我已经通过在chrome上通过Advance rest客户端应用程序发送json负载来测试我的Web服务,并且它返回json响应....但是当我使用Volley尝试它时,它返回了onErrorResponse。 在此先感谢您能告诉我如何解决此问题。
Json payLoad:
{"country":"isreal","mobile":"009988778"}
码
private void processLogin() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.LOGIN_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("JSON response", "JSON Posting" + response.toString());
hideProgessDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(ERROR_TAG, "Error: " + volleyError.getMessage());
hideProgessDialog();
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
@Override
protected Map<String, String> getParams(){
String country_value = country.getSelectedItem().toString();
String mobile_value = mobile.getText().toString();
Map<String, String> params = new HashMap<>();
params.put("country",country_value);
params.put("mobile", mobile_value);
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, login_tag);
}
您正在做的是,您正在尝试将JSON作为Headers的一部分发送,但无法正常工作。
这就是您需要的-
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.LOGIN_URL, **->YOUJSONOBJECTHERE<-**, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("JSON response", "JSON Posting" + response.toString());
hideProgessDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(ERROR_TAG, "Error: " + volleyError.getMessage());
hideProgessDialog();
}
});
您需要将JSONObject
作为请求的一部分而不是请求标头的一部分发送。 尝试一下,让我来,如果它可以解决问题,否则我们将对其进行故障排除。
而且,由于您已经在使用JSONObjectRequest
,因此您无需设置内容类型或覆盖getParams()
直到或除非您需要在标头中发送一些额外的信息(例如AgentType,令牌等)。
覆盖getBodyContentType设置为json
Gson gson = new Gson(); final String json = gson.toJson(loginDTO); GsonRequest<EmailLoginRestResponse> jsObjRequest = new GsonRequest<EmailLoginRestResponse>( Request.Method.POST, url, EmailLoginRestResponse.class, null, this.createLoginRequestSuccessListener(), this.createLoginErrorListener()){ @Override public byte[] getBody() throws AuthFailureError { return json.getBytes(); } @Override public String getBodyContentType() { return "application/json; charset=" + this.getParamsEncoding(); } }; jsObjRequest.setShouldCache(false); this.mRequestQueue.add(jsObjRequest);
GsonRequest.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.