/** * 请求执行 * @param request the request to perform * @param additionalHeaders additional headers to be sent together with * {@link Request#getHeaders()} * @return * @throws IOException * @throws AuthFailureError */ @Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { //传入request 进行创建封装过后的httprequest子类 httpurlrequest HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
public String getAuthToken() throws AuthFailureError { AccountManagerFuture<Bundle> future = this.mAccountManager.getAuthToken(this.mAccount, this.mAuthTokenType, this.mNotifyAuthFailure, null, null); try { Bundle result = (Bundle) future.getResult(); String authToken = null; if (future.isDone() && !future.isCancelled()) { if (result.containsKey("intent")) { throw new AuthFailureError((Intent) result.getParcelable("intent")); } authToken = result.getString("authtoken"); } if (authToken != null) { return authToken; } throw new AuthFailureError("Got null auth token for type: " + this.mAuthTokenType); } catch (Exception e) { throw new AuthFailureError("Error while retrieving auth token", e); } }
/** * @param apiTag tag to uniquely distinguish Volley requests. Null is allowed * @param url URL to fetch the string at * @param httpMethod the request method to use (GET or POST) * @param params A {@link JSONObject} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param headers optional Http headers * @param serverCallback Listener to receive the String response */ public void placeJsonObjectRequest(@Nullable final String apiTag, String url, int httpMethod, @Nullable JSONObject params, final @Nullable HashMap<String, String> headers, final ServerCallback serverCallback) { Request request = new JsonObjectRequest(httpMethod, url, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { serverCallback.onAPIResponse(apiTag, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { serverCallback.onErrorResponse(apiTag, error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers != null ? headers : super.getHeaders(); } }; request.setRetryPolicy(retryPolicy); addToRequestQueue(request); }
@SuppressWarnings("deprecation") @Override public String getAuthToken() throws AuthFailureError { AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null); Bundle result; try { result = future.getResult(); } catch (Exception e) { throw new AuthFailureError("Error while retrieving auth token", e); } String authToken = null; if (future.isDone() && !future.isCancelled()) { if (result.containsKey(AccountManager.KEY_INTENT)) { Intent intent = result.getParcelable(AccountManager.KEY_INTENT); throw new AuthFailureError(intent); } authToken = result.getString(AccountManager.KEY_AUTHTOKEN); } if (authToken == null) { throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType); } return authToken; }
public void execute() { final String url = URL + "/upvote"; StringRequest req = new StringRequest(Request.Method.POST, url, this, this) { @Override public HashMap<String, String> getHeaders() { return getDefaultHeaders(); } @Override public byte[] getBody() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username", mUsername); params.put("guid", mGuid); return new JSONObject(params).toString().getBytes(); } }; req.setRetryPolicy(new DefaultRetryPolicy( ASYNC_CONNECTION_NORMAL_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 0)); VolleyRequestQueue.getInstance().addToRequestQueue(req); }
@Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", getContentType()); if (onInterceptRequest != null) { onInterceptRequest.interceptHeader(headers); } if (!settings.mapHeaders.isEmpty()) { for (Map.Entry<String, String> entry : settings.mapHeaders.entrySet()) { headers.put(entry.getKey(), entry.getValue()); } } return headers; }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { mLastUrl = request.getUrl(); mLastHeaders = new HashMap<String, String>(); if (request.getHeaders() != null) { mLastHeaders.putAll(request.getHeaders()); } if (additionalHeaders != null) { mLastHeaders.putAll(additionalHeaders); } try { mLastPostBody = request.getBody(); } catch (AuthFailureError e) { mLastPostBody = null; } return mResponseToReturn; }
public void execute() { final String url = URL + "/register"; isRegistering = true; StringRequest req = new StringRequest(Request.Method.POST, url, this, this) { @Override public Map<String, String> getHeaders() { return getDefaultHeaders(); } @Override public byte[] getBody() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username", mUsername); params.put("device", "android"); params.put("pushID", mPushID); return new JSONObject(params).toString().getBytes(); } }; req.setRetryPolicy(new DefaultRetryPolicy( ASYNC_CONNECTION_EXTENDED_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 0)); VolleyRequestQueue.getInstance().addToRequestQueue(req); }
public void execute() { final String url = URL + "/remind"; StringRequest req = new StringRequest(Request.Method.POST, url, this, this) { @Override public HashMap<String, String> getHeaders() { return getDefaultHeaders(); } @Override public byte[] getBody() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("fromUsername", mUsername); params.put("toUsername", mToUsername); params.put("guid", mGuid); params.put("isRemindingRef", isRemindingRef ? "1" : "0"); return new JSONObject(params).toString().getBytes(); } }; req.setRetryPolicy(new DefaultRetryPolicy( ASYNC_CONNECTION_NORMAL_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 0)); VolleyRequestQueue.getInstance().addToRequestQueue(req); }
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
@Test(expected = AuthFailureError.class) public void resultContainsIntent() throws Exception { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture); when(mFuture.getResult()).thenReturn(bundle); when(mFuture.isDone()).thenReturn(true); when(mFuture.isCancelled()).thenReturn(false); mAuthenticator.getAuthToken(); }
private void getActions(final DeviceDAO device) { Log.d(TAG, "TODO getActions"); String uri = Uri.parse(String.format("http://%s:%s/", device.getIP(), device.getPort())) .buildUpon().build().toString(); String credentials = device.getUsername() + ":" + device.getPassword(); byte[] t = credentials.getBytes(); byte[] auth = Base64.encode(t, Base64.DEFAULT); final String basicAuthValue = new String(auth); requestQueue.add(new StringRequest(Request.Method.POST, uri, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", "Basic " + basicAuthValue); params.put("Connection", "close"); return params; } }); }
@Override public byte[] getBody() throws AuthFailureError { if(entity == null) { return null; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { entity.writeTo(bos); } catch (IOException e) { VolleyLog.e("IOException writing to ByteArrayOutputStream"); } return bos.toByteArray(); }
/** * Returns a list of extra HTTP headers to go along with this request. Can * throw <b>AuthFailureError</b> as authentication may be required to * provide these values. * @throws AuthFailureError In the event of auth failure * @return Map<String, String> */ @Override @NonNull public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> currentHeader = new HashMap<>(super.getHeaders()); currentHeader.putAll(this.headers); String bodyContentType = getBodyContentType(); if (bodyContentType == null && currentHeader.containsKey("Content-Type")) { currentHeader.remove("Content-Type"); } return currentHeader; }
private void pushAnswer() { String url = SERVER + KEY + "/questions/" + questionId + "/answers/" + uid; Log.i("URL", url); Map<String, JSONObject> params = new HashMap<String, JSONObject>(); JSONObject answer = new JSONObject(buildParams()); Log.i("Answer", answer.toString()); params.put("answer", answer); Log.i("AnswerFull", params.toString()); JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i("Response", response.toString()); nextQuestion(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "VolleyError Occurred", error); FirebaseCrash.report(error); nextQuestion(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); return headers; } }; queue.add(req); }
@Override public void loadPhoneNumberInfo(final String phoneNumber, final OnQueryPhoneNumberListener listener) { mQueryPhoneNumberHashMap = PhoneNumberInfoLab.get().getPhoneNumberInfoHashMap(); PhoneNumberInfo phoneNumberInfo = mQueryPhoneNumberHashMap.get(phoneNumber); if (phoneNumberInfo == null) { StringRequest request = new StringRequest(Request.Method.POST, Constant.JUHE_URL_POST, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.i(TAG, response); PhoneNumberInfo pni = JSONParser.parseJSON(response); mQueryPhoneNumberHashMap.put(phoneNumber, pni); listener.onSuccess(pni); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onError(error.toString()); } }){ /* 重写getParams() 用户在Volley中使用post方式请求数据中参数的传递 */ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> hashMap = new HashMap<>(); hashMap.put("phone", phoneNumber); hashMap.put("key", Constant.JUHE_API_KEY); return hashMap; } }; request.setTag(Constant.VOLLEY_TAG); //设置标签 MyApplication.getHttpQueues().add(request);//加入请求队列 } else { listener.onSuccess(phoneNumberInfo); // 若hashMap中已经有过记录,则直接显示 } }
private String volleyPostStringRequest() { StringRequest request = new StringRequest(Request.Method.POST, Constant.JUHE_URL_POST, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }){ /* getParams() 用户在Volley中使用post方式请求数据中参数的传递 */ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> hashMap = new HashMap<>(); hashMap.put("phone", "13429667914"); hashMap.put("key", "562609042fbd47baa063b1a2c4637758"); return hashMap; } }; request.setTag(STRING_POST_TAG); MyApplication.getHttpQueues().add(request); return request.getTag().toString(); }
public static void RequestPost(Context context, String url, String tag, Map<String, String> params, VolleyInterface volleyInterface) { MyApplication.getHttpQueues().cancelAll(tag); sStringRequest = new StringRequest(url, volleyInterface.loadingListener(), volleyInterface.errorListener()){ @Override protected Map<String, String> getParams() throws AuthFailureError { return super.getParams(); } }; sStringRequest.setTag(tag); MyApplication.getHttpQueues().add(sStringRequest); MyApplication.getHttpQueues().start(); }
@Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = super.getHeaders(); if (headers == null || headers.equals(Collections.emptyMap())) { headers = new HashMap<String, String>(); } if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { headers.putAll(apiHeaders); } if(contentType != null) { headers.put("Content-Type", contentType); } return headers; }
@Override public Map<String, String> getHeaders() throws AuthFailureError { if (mHeaders != null && mHeaders.size() != 0) { return mHeaders; } return super.getHeaders(); }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (this.mUrlRewriter != null) { String rewritten = this.mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } HttpURLConnection connection = openConnection(new URL(url), request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, (String) map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); if (connection.getResponseCode() == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection .getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0))); } } return response; }
public void execute() { final String url = URL + "/newgoal"; StringRequest req = new StringRequest(Request.Method.POST, url, this, this) { @Override public HashMap<String, String> getHeaders() { return getDefaultHeaders(); } @Override public byte[] getBody() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username", mUsername); params.put("start", String.valueOf(mStart)); params.put("end", String.valueOf(mEnd)); params.put("wager", String.valueOf(mWager)); params.put("encouragement", mEncouragement); params.put("referee", mReferee); params.put("title", mTitle); params.put("isGoalPublic", isGoalPublic ? "1" : "0"); return new JSONObject(params).toString().getBytes(); } }; req.setRetryPolicy(new DefaultRetryPolicy( ASYNC_CONNECTION_EXTENDED_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 0)); VolleyRequestQueue.getInstance().addToRequestQueue(req); }
@Test(expected = AuthFailureError.class) public void missingAuthToken() throws Exception { Bundle bundle = new Bundle(); when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture); when(mFuture.getResult()).thenReturn(bundle); when(mFuture.isDone()).thenReturn(true); when(mFuture.isCancelled()).thenReturn(false); mAuthenticator.getAuthToken(); }
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty("Content-Type", request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
@SuppressWarnings("deprecation") private static void setConnectionParametersForRequest(okhttp3.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // Ensure backwards compatibility. Volley assumes a request with a null body is a GET. byte[] postBody = request.getPostBody(); if (postBody != null) { builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody)); } break; case Request.Method.GET: builder.get(); break; case Request.Method.DELETE: builder.delete(); break; case Request.Method.POST: builder.post(createRequestBody(request)); break; case Request.Method.PUT: builder.put(createRequestBody(request)); break; case Request.Method.HEAD: builder.head(); break; case Request.Method.OPTIONS: builder.method("OPTIONS", null); break; case Request.Method.TRACE: builder.method("TRACE", null); break; case Request.Method.PATCH: builder.patch(createRequestBody(request)); break; default: throw new IllegalStateException("Unknown method type."); } }
@Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); /* params.put("Cookie","__test=44c3613f5fdf5542f710c31f6a68779a; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"); params.put("Content-Type", "application/json; charset=utf-8"); */ return params; }
protected void SendRequest() { SharedPreferences sharedPreferences = getSharedPreferences(UserPref.getSharedPrefName(), Context.MODE_PRIVATE); final String LenderType = sharedPreferences.getString(UserPref.getLendertypeSharedPref(),"Null"); StringRequest stringGetRequest = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/searchloansgrade.php", new Response.Listener<String>() { @Override public void onResponse(String response) { ParseJSON(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(LoanSearchActivity.this,error.toString(),Toast.LENGTH_SHORT).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put(UserPref.getlenderType(), LenderType); params.put(UserPref.getKeyGrade(), GradeStr); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringGetRequest); }