Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig custom.

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:co.paralleluniverse.fibers.dropwizard.FiberHttpClientBuilder.java

/**
 * Map the parameters in HttpClientConfiguration to a BasicHttpParams object
 *
 * @return a BasicHttpParams object from the HttpClientConfiguration
 *///from   w ww.  j  av  a  2  s  .c  om
protected RequestConfig createHttpParams() {
    RequestConfig.Builder rcb = RequestConfig.custom();
    rcb.setCookieSpec(CookieSpecs.BEST_MATCH);
    if (configuration.isCookiesEnabled())
        rcb.setCookieSpec(CookieSpecs.BEST_MATCH);
    else
        rcb.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
    rcb.setStaleConnectionCheckEnabled(false);
    return rcb.build();
}

From source file:org.apache.felix.http.itest.SessionHandlingTest.java

@Test
public void testSessionAttributes() throws Exception {
    setupContext("test1", "/");
    setupContext("test2", "/");

    setupLatches(2);/*ww  w.j a v  a  2s . c  o  m*/

    setupServlet("foo", new String[] { "/foo" }, 1, "test1");
    setupServlet("bar", new String[] { "/bar" }, 2, "test2");

    assertTrue(initLatch.await(5, TimeUnit.SECONDS));

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(new BasicCookieStore()).build();

    JSONObject json;

    // session should not be available
    // check for foo servlet
    json = getJSONResponse(httpclient, "/foo");
    assertFalse(((Boolean) json.get("session")).booleanValue());

    // check for bar servlet
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(((Boolean) json.get("session")).booleanValue());

    // create session for  context of servlet foo
    // check session and session attribute
    json = getJSONResponse(httpclient, "/foo?create=true");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    final String sessionId1 = (String) json.get("sessionId");
    assertNotNull(sessionId1);

    // check session for servlet bar (= no session)
    json = getJSONResponse(httpclient, "/bar");
    assertFalse(((Boolean) json.get("session")).booleanValue());
    // another request to servlet foo, still the same
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    assertEquals(sessionId1, json.get("sessionId"));

    // create session for second context
    json = getJSONResponse(httpclient, "/bar?create=true");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test2", json.get("value"));
    final String sessionId2 = (String) json.get("sessionId");
    assertNotNull(sessionId2);
    assertFalse(sessionId1.equals(sessionId2));

    // and context foo is untouched
    json = getJSONResponse(httpclient, "/foo");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test1", json.get("value"));
    assertEquals(sessionId1, json.get("sessionId"));

    // invalidate session for foo context
    json = getJSONResponse(httpclient, "/foo?destroy=true");
    assertFalse(((Boolean) json.get("session")).booleanValue());
    // bar should be untouched
    json = getJSONResponse(httpclient, "/bar");
    assertTrue(((Boolean) json.get("session")).booleanValue());
    assertEquals("test2", json.get("value"));
    assertEquals(sessionId2, json.get("sessionId"));
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;//from  ww  w  .java2s  .  c o m
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpPut putRequest = new HttpPut(uri);

    // setting the connection timeout (idle connection, configured in seconds)
    putRequest.setConfig(
            RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());

    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(
                    new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView;
        try {
            clusterView = clusterViewService.getLocalClusterView();
        } catch (UndefinedClusterViewException e) {
            // SLING-5030 : then we cannot ping
            logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e);
            return;
        }
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterView.getInstances().iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(putRequest, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            putRequest.addHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            final StringEntity plaintext = new StringEntity(p, "UTF-8");
            plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            putRequest.setEntity(plaintext);
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        putRequest.addHeader("Accept-Encoding", "gzip");
        final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - "
                    + response.getStatusLine().getReasonPhrase());
        }
        lastStatusCode = response.getStatusLine().getStatusCode();
        lastResponseEncoding = null;
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        putRequest.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static int getNotificationCount(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols,
        String[] cipherSuites) {// w  w  w  .  j a  v a  2s  .co m
    CloseableHttpClient client = null;
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    int notificationCount = 0;

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            List<Integer> notificationIds = mapper.readValue(
                    IOUtils.toString(responseEntity.getContent(), responseCharset).trim(),
                    new TypeReference<List<Integer>>() {
                    });
            for (int id : notificationIds) {
                if (!archivedNotifications.contains(id)) {
                    notificationCount++;
                }
            }
        }
    } catch (Exception e) {
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
    return notificationCount;
}

From source file:ee.ria.xroad.common.util.AbstractHttpSender.java

protected RequestConfig getRequestConfig() {
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(connectionTimeout);
    rb.setConnectionRequestTimeout(connectionTimeout);
    rb.setSocketTimeout(socketTimeout);/*from   w ww .  j  av a  2 s.c o  m*/

    return rb.build();
}

From source file:org.lokra.seaweedfs.core.Connection.java

/**
 * Start up polls for core leader.//from w  w  w.j  a  v  a  2 s .co  m
 */
void startup() {
    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectionTimeout)
            .build();
    if (this.enableFileStreamCache) {
        if (this.fileStreamCacheStorage == null) {
            final CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(this.fileStreamCacheEntries)
                    .setMaxObjectSize(this.fileStreamCacheSize).setHeuristicCachingEnabled(true)
                    .setHeuristicCoefficient(0.8f).build();
            this.httpClient = CachingHttpClients.custom().setCacheConfig(cacheConfig)
                    .setConnectionManager(this.clientConnectionManager).setDefaultRequestConfig(requestConfig)
                    .build();
        } else {
            this.httpClient = CachingHttpClients.custom().setHttpCacheStorage(this.fileStreamCacheStorage)
                    .setConnectionManager(this.clientConnectionManager).setDefaultRequestConfig(requestConfig)
                    .build();
        }
    } else {
        this.httpClient = HttpClients.custom().setConnectionManager(this.clientConnectionManager)
                .setDefaultRequestConfig(requestConfig).build();
    }
    initCache();
    this.pollClusterStatusThread.updateSystemStatus(true, true);
    this.pollClusterStatusThread.start();
    this.idleConnectionMonitorThread.start();
    log.info("seaweedfs master server connection is startup");
}

From source file:com.tremolosecurity.scale.config.ScaleCommonConfig.java

public HttpClientInfo createHttpClientInfo() {

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx, new AllowAllHostnameVerifier());
    PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf)
            .register("https", sslsf).build();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .setRedirectsEnabled(true).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

    return new HttpClientInfo(cm, globalConfig);
}

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

@SuppressWarnings("deprecation")
public static CloseableHttpClient makeHttpClient4(boolean usePool) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setDefaultRequestConfig(
            RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build());

    if (usePool) {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

        int maxTotalConnections = 100;
        try {/*from   ww w .  j ava2s.  c  om*/
            maxTotalConnections = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_TOTAL_CONNECTIONS))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine.warn("Unable to retrieve the max number of connections; defaults to 100.");
        }

        int maxConnectionsPerHost = 50;
        try {
            maxConnectionsPerHost = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_CONNECTIONS_PER_HOST))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine
                    .warn("Unable to retrieve the max number of connections per host; defaults to 100.");
        }

        connManager.setDefaultMaxPerRoute(maxConnectionsPerHost);
        connManager.setMaxTotal(maxTotalConnections);

        httpClientBuilder.setConnectionManager(connManager);
    }

    return httpClientBuilder.build();
}

From source file:edu.mit.scratch.Scratch.java

public static ScratchSession register(final String username, final String password, final String gender,
        final int birthMonth, final String birthYear, final String country, final String email)
        throws ScratchUserException {
    // Long if statement to verify all fields are valid
    if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2)
            || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0)
            || (email.length() < 5)) {
        throw new ScratchUserException(); // TDL: Specify reason for failure
    } else {//w  w  w  .ja v  a2 s.com
        try {
            final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
                    .build();

            final CookieStore cookieStore = new BasicCookieStore();
            final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
            lang.setDomain(".scratch.mit.edu");
            lang.setPath("/");
            cookieStore.addCookie(lang);

            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
            CloseableHttpResponse resp;

            final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                    .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                    .addHeader("X-Requested-With", "XMLHttpRequest").build();
            try {
                resp = httpClient.execute(csrf);
            } catch (final IOException e) {
                e.printStackTrace();
                throw new ScratchUserException();
            }
            try {
                resp.close();
            } catch (final IOException e) {
                throw new ScratchUserException();
            }

            String csrfToken = null;
            for (final Cookie c : cookieStore.getCookies())
                if (c.getName().equals("scratchcsrftoken"))
                    csrfToken = c.getValue();

            /*
             * try {
             * username = URLEncoder.encode(username, "UTF-8");
             * password = URLEncoder.encode(password, "UTF-8");
             * birthMonth = Integer.parseInt(URLEncoder.encode("" +
             * birthMonth, "UTF-8"));
             * birthYear = URLEncoder.encode(birthYear, "UTF-8");
             * gender = URLEncoder.encode(gender, "UTF-8");
             * country = URLEncoder.encode(country, "UTF-8");
             * email = URLEncoder.encode(email, "UTF-8");
             * } catch (UnsupportedEncodingException e1) {
             * e1.printStackTrace();
             * }
             */

            final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken);
            csrfCookie.setDomain(".scratch.mit.edu");
            csrfCookie.setPath("/");
            cookieStore.addCookie(csrfCookie);
            final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
            debug.setDomain(".scratch.mit.edu");
            debug.setPath("/");
            cookieStore.addCookie(debug);

            httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                    .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();

            /*
             * final String data = "username=" + username + "&password=" +
             * password + "&birth_month=" + birthMonth + "&birth_year=" +
             * birthYear + "&gender=" + gender + "&country=" + country +
             * "&email=" + email +
             * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken="
             * + csrfToken;
             * System.out.println(data);
             */

            final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN);
            builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN);
            builder.addTextBody("country", country, ContentType.TEXT_PLAIN);
            builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN);
            builder.addTextBody("email", email, ContentType.TEXT_PLAIN);
            builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN);
            builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("password", password, ContentType.TEXT_PLAIN);
            builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN);
            builder.addTextBody("username", username, ContentType.TEXT_PLAIN);
            builder.addTextBody("usernames_and_messages",
                    "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>",
                    ContentType.TEXT_PLAIN);

            final HttpUriRequest createAccount = RequestBuilder.post()
                    .setUri("https://scratch.mit.edu/accounts/register_new_user/")
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/")
                    .addHeader("Origin", "https://scratch.mit.edu")
                    .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1")
                    .addHeader("Accept-Language", "en-US,en;q=0.8")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken)
                    .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id",
                            "54255D9A-9771-4CAC-9052-50C8AB7469E0")
                    .setEntity(builder.build()).build();
            resp = httpClient.execute(createAccount);
            System.out.println("REGISTER:" + resp.getStatusLine());
            final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            final StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null)
                result.append(line);
            System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase()
                    + "\n" + resp.getStatusLine());
            if (resp.getStatusLine().getStatusCode() != 200)
                throw new ScratchUserException();
            resp.close();
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
        try {
            return Scratch.createSession(username, password);
        } catch (final Exception e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }
    }
}