import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class LoginService {
public interface VolleyCallback{
void onSuccess(String result);
}
// method to call login webservice
public void loginWebservice(final Context context, final ProgressDialog Dialog, final String username, final String password, final VolleyCallback callback) {
Dialog.setMessage("Please wait..");
Dialog.show();
String POST_Login_URL = "http://example.com";
StringRequest stringRequest = new StringRequest(Request.Method.POST, POST_Login_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("response", response);
Dialog.dismiss();
try {
JSONObject myJson = new JSONObject(response);
String authenticated = myJson.optString("status");
if (authenticated.equals("true")) {
callback.onSuccess(authenticated);
} else {
Toast.makeText(context, "Invalid Username/Password", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Dialog.dismiss();
Log.d("errorString", error.toString());
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
public String getBodyContentType() {
return "text/plain; charset=" + getParamsEncoding();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Content-Type", "text/plain; charset="+ getParamsEncoding());
return map;
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
String json = convert(params);
if (json.length() < 3)
return ("{}").getBytes();
// log(json);
return json.getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "getBody(): request has no json");
e.printStackTrace();
}
return new byte[0];
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public static String convert(Map<String, String> map) {
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}
}
在上面的代码中,我无法将标题内容类型application / json更新为text / plain。我重写了getBodyContentType()方法和getHeaders()方法但是当我调试代码时,content-type显示了application / json,即我从服务器获得了500个错误代码。 Web api工作正常。因为我使用自己的网络代码检查了api。