在我的活动中,它检查用户凭据并返回会话ID和相关信息(如果有效)。方法是POST。参数必须作为JSON发送。
{
"params": {
"context": {},
"db": "testing",
"login": "admin",
"password": "admin"
}
}
所以我创建了一个JSONObject并发送它,因为它是Header.I我在POSTMAN中得到响应。但是当我调用它时我得到的错误是什么。可以帮助我吗?
private void volleyLogin() throws JSONException {
mProgressView.setVisibility(View.VISIBLE);
JSONObject one = new JSONObject();
one.put("context",new JSONObject());
one.put("db","testing");
one.put("login","admin");
one.put("password","admin");
JSONObject params = new JSONObject();
params.put("params",one);
HashMap<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json; charset=utf-8");
RequestQueue requestQueue = Volley.newRequestQueue(this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
ApiConstants.URL_AUTHENTICATE,params,header, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println("Response"+response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("VolleyError"+error);
}
}
);
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(120),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
System.out.println("jsObjRequest"+jsObjRequest);
requestQueue.add(jsObjRequest);
}
这是自定义请求类
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private JSONObject jsonObjectParams;
private Map<String, String> headers;
public CustomRequest(int method,String url, JSONObject jsonObjectParams,Map<String, String> headers,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.jsonObjectParams = jsonObjectParams;
this.headers= headers;
System.out.println("method"+method);
System.out.println("url"+url);
System.out.println("jsonObjectParams"+jsonObjectParams);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
volleyError = error;
}
return volleyError;
}
}
答案 0 :(得分:0)
您可以尝试这样的事情:
创建一个单一类VolleyDispatcher,它保存来自凌空的RequestQueue。
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return requestQueue;
}
/**
* Recreates the request queue using username/password https auth.
*/
public void recreateRequestQueue() {
if (!AppUtil.isEmpty(AppConstants.USERNAME) && !AppUtil.isEmpty(AppConstants.PASSWORD)) {//check if a user is logged in so that the https auth can be created if necessary
if (requestQueue != null) {
requestQueue.stop();
requestQueue = null;
}
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext(), new HurlCustomStack());
}
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
在执行任何截击请求之前调用recreateRequestQueue
实施自定义HurlStack
public class HurlCustomStack extends HurlStack {
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
// Workaround for the M release HttpURLConnection not observing the
// HttpURLConnection.setFollowRedirects() property.
// https://code.google.com/p/android/issues/detail?id=194495
// connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());
return HttpUrlConnectionHelper.getInstance().createHttpUrlConnection(url);
}
}
客户端创建方法:
public HttpURLConnection createHttpUrlConnection(URL url) throws IOException {
Log.d(TAG, "Create http url connection with url : " + url.toString());
HttpURLConnection httpConnection = null;
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
httpConnection = https;
} else {
httpConnection = (HttpURLConnection) url.openConnection();
}
httpConnection.setReadTimeout(TIMEOUT);
httpConnection.setConnectTimeout(TIMEOUT);
String basicAuth = "Basic " + new String(Base64.encode((AppConstants.USERNAME + ":" + AppConstants.PASSWORD).getBytes(), Base64.NO_WRAP));
httpConnection.setRequestProperty("Authorization", basicAuth);
httpConnection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
return httpConnection;
}
现在,每次要发出请求时,只需使用addToRequestQueue
类中的VolleyDispatcher
方法即可。