com.android.volley.AuthFailureError Java Examples

The following examples show how to use com.android.volley.AuthFailureError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicNetworkTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void unauthorized() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    HttpResponse fakeResponse = new HttpResponse(401, Collections.<Header>emptyList());
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #2
Source File: MockHttpStack.java    From device-database with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: BaseHttpStackTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void legacyResponseWithBody() throws Exception {
    BaseHttpStack stack =
            new BaseHttpStack() {
                @Override
                public HttpResponse executeRequest(
                        Request<?> request, Map<String, String> additionalHeaders)
                        throws IOException, AuthFailureError {
                    assertSame(REQUEST, request);
                    assertSame(ADDITIONAL_HEADERS, additionalHeaders);
                    return new HttpResponse(
                            12345, Collections.<Header>emptyList(), 555, mContent);
                }
            };
    org.apache.http.HttpResponse resp = stack.performRequest(REQUEST, ADDITIONAL_HEADERS);
    assertEquals(12345, resp.getStatusLine().getStatusCode());
    assertEquals(0, resp.getAllHeaders().length);
    assertEquals(555L, resp.getEntity().getContentLength());
    assertSame(mContent, resp.getEntity().getContent());
}
 
Example #4
Source File: BaseHttpStackTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void legacyRequestWithoutBody() throws Exception {
    BaseHttpStack stack =
            new BaseHttpStack() {
                @Override
                public HttpResponse executeRequest(
                        Request<?> request, Map<String, String> additionalHeaders)
                        throws IOException, AuthFailureError {
                    assertSame(REQUEST, request);
                    assertSame(ADDITIONAL_HEADERS, additionalHeaders);
                    return new HttpResponse(12345, Collections.<Header>emptyList());
                }
            };
    org.apache.http.HttpResponse resp = stack.performRequest(REQUEST, ADDITIONAL_HEADERS);
    assertEquals(12345, resp.getStatusLine().getStatusCode());
    assertEquals(0, resp.getAllHeaders().length);
    assertNull(resp.getEntity());
}
 
Example #5
Source File: AndroidAuthenticator.java    From device-database with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: BasicNetworkTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    HttpResponse fakeResponse = new HttpResponse(403, Collections.<Header>emptyList());
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #7
Source File: HttpClientStack.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    // 创建一个 Apache HTTP 请求
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    // 添加 performRequest 方法传入的 头信息
    addHeaders(httpRequest, additionalHeaders);
    // 添加 Volley 抽象请求了 Request 设置的 头信息
    addHeaders(httpRequest, request.getHeaders());
    // 回调( 如果被覆写的话 ) 预请求 方法
    onPrepareRequest(httpRequest);
    // 获取 Apache 请求的 HttpParams 对象
    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);
    // 设置 SO_TIMEOUT
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    // 开始执行请求
    return mClient.execute(httpRequest);
}
 
Example #8
Source File: FakeRequestQueue.java    From openshop.io-android with MIT License 6 votes vote down vote up
@Override
public Request add(Request request) {
    Timber.d("FakeRequestQueue is used");
    Timber.d("New request %s is added with priority %s", request.getUrl(), request.getPriority());
    try {
        if (request.getBody() == null) {
            Timber.d("Body is null");
        } else {
            Timber.d("Body: %s", new String(request.getBody()));
        }
    } catch (AuthFailureError e) {
        // cannot do anything
    }
    request.setShouldCache(false);
    return super.add(request);
}
 
Example #9
Source File: RegisterModelImp.java    From HightCopyWX with Apache License 2.0 6 votes vote down vote up
@Override
public void sendAll(final sendAllListener listener, String userName, String number) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UrlUtils.registerUrl(userName, number)
            , null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            listener.onSendSucceed();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            listener.onError();
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> header = new HashMap<>();
            header.put("Authorization", "key=" + App.APP_SECRET_KEY);
            return header;
        }
    };
    VolleyUtils.addQueue(request, "registerRequest");
}
 
Example #10
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #11
Source File: ChatModelImp.java    From HightCopyWX with Apache License 2.0 6 votes vote down vote up
@Override
public void requestData(final requestListener listener, final String chatContent, final String number, final String regId, final ChatMessageDataHelper helper) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, UrlUtils.chatUrl(chatContent, number, regId)
            , null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            mChatMessageInfo = new ChatMessageInfo(chatContent, 1, CalendarUtils.getCurrentDate(),
                    number, regId, SPUtils.getString("userPhone", ""));
            listener.onSucceed(mChatMessageInfo, helper);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.d("TAG", volleyError.getMessage());
            listener.onError(volleyError.getMessage());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> header = new HashMap<>();
            header.put("Authorization", "key=" + App.APP_SECRET_KEY);
            return header;
        }
    };
    VolleyUtils.addQueue(jsonObjectRequest, "chatRequest");
}
 
Example #12
Source File: UserInfoActivity.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
private void readNetBuffer() {
    StringRequest getUserInfo = new PowerStringRequest(Request.Method.POST,
            NONoConfig.makeNONoSonURL("/quickask_get_userinfo_home.php"),
            new PowerListener() {
                @Override
                public void onCorrectResponse(String s) {
                    super.onCorrectResponse(s);
                    try{
                        userInfo =  new Gson().fromJson(s,new TypeToken<UserInfo>(){}.getType());
                    }catch(Exception e){
                        Toast.makeText(UserInfoActivity.this,"获取用户信息错误(等级:严重),请联系开发者!",Toast.LENGTH_SHORT).show();
                    }

                    UpdateUI(userInfo);
                }

                @Override
                public void onJSONStringParseError() {
                    super.onJSONStringParseError();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String,String> params = new HashMap<>();
            params.put("me_id",MyApp.userInfo.userId);
            params.put("user_id",String.valueOf(userInfo.data.user_id));

            return params;
        }
    };
    MyApp.getInstance().volleyRequestQueue.add(getUserInfo);
}
 
Example #13
Source File: VolleyHurlStackMixin.java    From android-perftracking with MIT License 5 votes vote down vote up
@ReplaceMethod
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
    throws IOException, AuthFailureError {

  int id = Tracker.startMethod(request, "performRequest");

  try {
    return performRequest(request, additionalHeaders);
  } finally {
    Tracker.endMethod(id);
  }
}
 
Example #14
Source File: HurlStack.java    From device-database with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #15
Source File: HurlStack.java    From device-database with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        case Method.GET:
            // Not necessary to set the request method because connection defaults to GET but
            // being explicit here.
            connection.setRequestMethod("GET");
            break;
        case Method.DELETE:
            connection.setRequestMethod("DELETE");
            break;
        case Method.POST:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case Method.PUT:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example #16
Source File: HttpClientStack.java    From device-database with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #17
Source File: HttpClientStack.java    From device-database with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: GetRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #19
Source File: DeleteRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #20
Source File: DeleteRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@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();
}
 
Example #21
Source File: DeleteRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@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;
}
 
Example #22
Source File: PutRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #23
Source File: GetRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@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;
}
 
Example #24
Source File: PostRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@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;
}
 
Example #25
Source File: PostRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@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();
}
 
Example #26
Source File: OkHttpStack.java    From android with MIT License 5 votes vote down vote up
private static RequestBody createRequestBody(Request r) throws AuthFailureError {
    byte[] body = r.getBody();
    if (body == null) {
        return null;
    }
    return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
}
 
Example #27
Source File: GsonRequest.java    From openshop.io-android with MIT License 5 votes vote down vote up
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<>();
    headers.put("Client-Version", MyApplication.APP_VERSION);
    headers.put("Device-Token", MyApplication.ANDROID_ID);

    // Determine if request should be authorized.
    if (accessToken != null && !accessToken.isEmpty()) {
        String credentials = accessToken + ":";
        String encodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
        headers.put("Authorization", "Basic " + encodedCredentials);
    }
    return headers;
}
 
Example #28
Source File: AndroidAuthenticatorTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #29
Source File: AndroidAuthenticatorTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source File: HuanXinUserManager.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
public static void put(final String id, final EaseUser easeUser){
    MyApp.getInstance().volleyRequestQueue.add(new StringRequest(Request.Method.POST,
            "http://2.diandianapp.sinaapp.com/quickask_get_userinfo_home.php",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    com.seki.noteasklite.DataUtil.Bean.UserInfo userInfo = new com.seki.noteasklite.DataUtil.Bean.UserInfo();
                    userInfo.data = new com.seki.noteasklite.DataUtil.Bean.UserInfo.Data();
                    userInfo.data.user_info_real_name = "佚名";
                    userInfo.data.user_info_headimg= NONoConfig.defaultHeadImg;
                    try{
                        userInfo =
                                new Gson().fromJson(s, new TypeToken<com.seki.noteasklite.DataUtil.Bean.UserInfo>() {
                                }.getType());
                    }catch (JsonSyntaxException jse){
                        Log.d(NONoConfig.TAG_NONo,"oops....,can not fingure out the user on NONo,may be admin on HuanXin");
                        userInfo.data.user_info_real_name = "外星人";
                    }
                    easeUser.setNick(userInfo.data.user_info_real_name);
                    easeUser.setAvatar(userInfo.data.user_info_headimg);

                    KeyValueDatabase keyValueDatabase = quickKVWeakReference.getDatabase();
                    keyValueDatabase.put(id, easeUser);
                    keyValueDatabase.persist();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("user_id", id);
            return params;
        }
    });

}