0
我想發送POST請求與paramteres到服務器。但後參數始終爲空。android-Volley JSONObjectRequest返回401錯誤
我試過幾個解決方案,從stackoverflow
但它沒有奏效。
我得到意外的響應代碼401 11.urlname
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("username", "[email protected]");
jsonParams.put("usertype", "userType");
jsonParams.put("apikey", "key");
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST,apiURL, new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String status=response.getString("status");
if (status.equals("success"))
{
txtResponse.setText("Valid user");
}
else {
txtResponse.setText("InValid USer");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError 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");
return headers;
}
};
AppController.getInstance().addToRequestQueue(myRequest, "tag");
我的應用程序控制器代碼是
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
嘗試使用StringRequest ......連我都面臨着同樣的問題......解決它使用StringRequest –
我已經試過了'StringRequest'它沒有工作 – iCoder