/** Perform appropriate backoff etc. extraction. */ public void interpretHTTPFailure(HttpResponse response) { // TODO: handle permanent rejection. long responseBackoff = (new SyncResponse(response)).totalBackoffInMilliseconds(); if (responseBackoff > 0) { callback.requestBackoff(responseBackoff); } if (response.getStatusLine() != null) { final int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 400: SyncStorageResponse storageResponse = new SyncStorageResponse(response); this.interpretHTTPBadRequestBody(storageResponse); break; case 401: /* * Alert our callback we have a 401 on a cluster URL. This GlobalSession * will fail, but the next one will fetch a new cluster URL and will * distinguish between "node reassignment" and "user password changed". */ callback.informUnauthorizedResponse(this, config.getClusterURL()); break; } } }
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null."); } int status = response.getStatusLine().getStatusCode(); if ((status >= HttpStatus.SC_OK) && !response.containsHeader(HTTP.DATE_HEADER)) { String httpdate = DATE_GENERATOR.getCurrentDate(); response.setHeader(HTTP.DATE_HEADER, httpdate); } }
public Multistatus handleResponse(HttpResponse response) throws SardineException, IOException { super.validateResponse(response); // Process the response from the server. HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); if (entity == null) { throw new SardineException( "No entity found in response", statusLine.getStatusCode(), statusLine.getReasonPhrase()); } return this.getMultistatus(entity.getContent()); }
@SuppressWarnings("unchecked") public ClientResponse execute(ClientRequest request) throws Exception { String uri = request.getUri(); final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod()); try { loadHttpMethod(request, httpMethod); final HttpResponse res = httpClient.execute(httpMethod, httpContext); final BaseClientResponse response = new BaseClientResponse(null, this); BaseClientResponseStreamFactory sf = new BaseClientResponseStreamFactory() { InputStream stream; public InputStream getInputStream() throws IOException { if (stream == null) { HttpEntity entity = res.getEntity(); if (entity == null) return null; stream = new SelfExpandingBufferredInputStream(entity.getContent()); } return stream; } public void performReleaseConnection() { // Apache Client 4 is stupid, You have to get the InputStream and close it if there is // an entity // otherwise the connection is never released. There is, of course, no close() method // on response // to make this easier. try { if (stream != null) { stream.close(); } else { InputStream is = getInputStream(); if (is != null) { is.close(); } } } catch (Exception ignore) { } } }; response.setStreamFactory(sf); response.setAttributes(request.getAttributes()); response.setStatus(res.getStatusLine().getStatusCode()); response.setHeaders(extractHeaders(res)); response.setProviderFactory(request.getProviderFactory()); return response; } finally { cleanUpAfterExecute(httpMethod); } }
public static StatusCode logout() { HttpResponse logoutResponse = Network.getRequest( "https://www.geocaching.com/login/default.aspx?RESET=Y&redir=http%3a%2f%2fwww.geocaching.com%2fdefault.aspx%3f"); String logoutData = Network.getResponseData(logoutResponse); if (logoutResponse != null && logoutResponse.getStatusLine().getStatusCode() == 503 && BaseUtils.matches(logoutData, GCConstants.PATTERN_MAINTENANCE)) { return StatusCode.MAINTENANCE; } Cookies.clearCookies(); Settings.setCookieStore(null); return StatusCode.NO_ERROR; }
private String dealWithError(HttpResponse httpResponse) throws WeiboException { StatusLine status = httpResponse.getStatusLine(); int statusCode = status.getStatusCode(); String result = ""; if (statusCode != HttpStatus.SC_OK) { result = readResult(httpResponse); String err = null; int errCode = 0; try { JSONObject json = new JSONObject(result); err = json.getString("error"); errCode = json.getInt("error_code"); WeiboException exception = new WeiboException(); exception.setError_code(errCode); exception.setOriError(err); throw exception; } catch (JSONException e) { e.printStackTrace(); } } return result; }
public static CaseInsensitiveMap<String> extractHeaders(HttpResponse response) { final CaseInsensitiveMap<String> headers = new CaseInsensitiveMap<String>(); for (Header header : response.getAllHeaders()) { headers.add(header.getName(), header.getValue()); } return headers; }
protected SilkHttpResponse performRequest(final HttpUriRequest request) throws SilkHttpException { if (mHeaders.size() > 0) { for (SilkHttpHeader header : mHeaders) request.setHeader(header.getName(), header.getValue()); } HttpResponse response; try { response = mClient.execute(request); } catch (Exception e) { reset(); throw new SilkHttpException(e); } int status = response.getStatusLine().getStatusCode(); if (status != 200) { reset(); throw new SilkHttpException(response); } reset(); return new SilkHttpResponse(response); }
/** Test that handleHTTPError does in fact backoff. */ @Test public void testBackoffCalledByHandleHTTPError() { try { final MockGlobalSessionCallback callback = new MockGlobalSessionCallback(TEST_CLUSTER_URL); SyncConfiguration config = new SyncConfiguration( TEST_USERNAME, new BasicAuthHeaderProvider(TEST_USERNAME, TEST_PASSWORD), new MockSharedPreferences(), new KeyBundle(TEST_USERNAME, TEST_SYNC_KEY)); final GlobalSession session = new MockGlobalSession(config, callback); final HttpResponse response = new BasicHttpResponse( new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), 503, "Illegal method/protocol")); response.addHeader( "X-Weave-Backoff", Long.toString(TEST_BACKOFF_IN_SECONDS)); // Backoff given in seconds. getTestWaiter() .performWait( WaitHelper.onThreadRunnable( new Runnable() { @Override public void run() { session.handleHTTPError( new SyncStorageResponse(response), "Illegal method/protocol"); } })); assertEquals(false, callback.calledSuccess); assertEquals(true, callback.calledError); assertEquals(false, callback.calledAborted); assertEquals(true, callback.calledRequestBackoff); assertEquals( TEST_BACKOFF_IN_SECONDS * 1000, callback.weaveBackoff); // Backoff returned in milliseconds. } catch (Exception e) { e.printStackTrace(); fail("Got exception."); } }
private String dealWithResponse(HttpResponse httpResponse) throws WeiboException { StatusLine status = httpResponse.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return dealWithError(httpResponse); } return readResult(httpResponse); }
@Override public void handleHttpResponse(final HttpResponse response) { final int status = response.getStatusLine().getStatusCode(); switch (status) { case 200: case 201: Log.d(LOGTAG, "Telemetry upload success."); break; default: Log.w(LOGTAG, "Telemetry upload failure. HTTP status: " + status); } }
// Interface to AsyncHttpRequest void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); String responseBody = null; try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, "UTF-8"); } } catch (IOException e) { sendFailureMessage(e, (String) null); } if (status.getStatusCode() >= 300) { sendFailureMessage( new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } }
/** * Download or refresh the copy of <code>url</code> in <code>file</code>. * * @param url the url of the document * @param file the file to save the document in * @return <code>true</code> if the existing file was up-to-date, <code>false</code> otherwise */ private boolean downloadOrRefreshCopy(final String url, final File file) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { if (!file.setLastModified(System.currentTimeMillis())) { makeFreshCopy(file); } return true; } } } catch (final Exception e) { Log.e("HtmlImage.downloadOrRefreshCopy", e); } } return false; }
private static void saveHeader( final String name, @Nullable final HttpResponse response, final File baseFile) { final Header header = response != null ? response.getFirstHeader(name) : null; final File file = filenameForHeader(baseFile, name); if (header == null) { FileUtils.deleteIgnoringFailure(file); } else { try { saveToFile(new ByteArrayInputStream(header.getValue().getBytes("UTF-8")), file); } catch (final UnsupportedEncodingException e) { // Do not try to display the header in the log message, as our default encoding is // likely to be UTF-8 and it will fail as well. Log.e("LocalStorage.saveHeader: unable to decode header", e); } } }
/** * Save an HTTP response to a file. * * @param response the response whose entity content will be saved * @param targetFile the target file, which will be created if necessary * @return true if the operation was successful, false otherwise, in which case the file will not * exist */ public static boolean saveEntityToFile(final HttpResponse response, final File targetFile) { if (response == null) { return false; } try { final boolean saved = saveToFile(response.getEntity().getContent(), targetFile); saveHeader(HEADER_ETAG, saved ? response : null, targetFile); saveHeader(HEADER_LAST_MODIFIED, saved ? response : null, targetFile); return saved; } catch (final IOException e) { Log.e("LocalStorage.saveEntityToFile", e); } return false; }
private String readResult(HttpResponse response) { HttpEntity entity = response.getEntity(); String result = ""; try { result = EntityUtils.toString(entity); } catch (IOException e) { AppLogger.e(e.getMessage()); ActivityUtils.showTips(R.string.timeout); } AppLogger.d(result); return result; }
private static StatusCode login(boolean retry) { final ImmutablePair<String, String> login = Settings.getLogin(); if (login == null || StringUtils.isEmpty(login.left) || StringUtils.isEmpty(login.right)) { Login.setActualStatus(cgeoapplication.getInstance().getString(R.string.err_login)); Log.e("Login.login: No login information stored"); return StatusCode.NO_LOGIN_INFO_STORED; } Login.setActualStatus( cgeoapplication.getInstance().getString(R.string.init_login_popup_working)); HttpResponse loginResponse = Network.getRequest("https://www.geocaching.com/login/default.aspx"); String loginData = Network.getResponseData(loginResponse); if (loginResponse != null && loginResponse.getStatusLine().getStatusCode() == 503 && BaseUtils.matches(loginData, GCConstants.PATTERN_MAINTENANCE)) { return StatusCode.MAINTENANCE; } if (StringUtils.isBlank(loginData)) { Log.e("Login.login: Failed to retrieve login page (1st)"); return StatusCode.CONNECTION_FAILED; // no loginpage } if (Login.getLoginStatus(loginData)) { Log.i( "Already logged in Geocaching.com as " + login.left + " (" + Settings.getMemberStatus() + ')'); Login.switchToEnglish(loginData); return StatusCode.NO_ERROR; // logged in } Cookies.clearCookies(); Settings.setCookieStore(null); final Parameters params = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$tbUsername", login.left, "ctl00$ContentBody$tbPassword", login.right, "ctl00$ContentBody$cbRememberMe", "on", "ctl00$ContentBody$btnSignIn", "Login"); final String[] viewstates = Login.getViewstates(loginData); if (isEmpty(viewstates)) { Log.e("Login.login: Failed to find viewstates"); return StatusCode.LOGIN_PARSE_ERROR; // no viewstates } Login.putViewstates(params, viewstates); loginResponse = Network.postRequest("https://www.geocaching.com/login/default.aspx", params); loginData = Network.getResponseData(loginResponse); if (StringUtils.isBlank(loginData)) { Log.e("Login.login: Failed to retrieve login page (2nd)"); // FIXME: should it be CONNECTION_FAILED to match the first attempt? return StatusCode.COMMUNICATION_ERROR; // no login page } if (Login.getLoginStatus(loginData)) { Log.i( "Successfully logged in Geocaching.com as " + login.left + " (" + Settings.getMemberStatus() + ')'); Login.switchToEnglish(loginData); Settings.setCookieStore(Cookies.dumpCookieStore()); return StatusCode.NO_ERROR; // logged in } if (loginData.contains("Your username/password combination does not match.")) { Log.i( "Failed to log in Geocaching.com as " + login.left + " because of wrong username/password"); return StatusCode.WRONG_LOGIN_DATA; // wrong login } Log.i("Failed to log in Geocaching.com as " + login.left + " for some unknown reason"); if (retry) { Login.switchToEnglish(loginData); return login(false); } return StatusCode.UNKNOWN_ERROR; // can't login }