Example usage for org.apache.http.entity.mime MultipartEntityBuilder build

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntityBuilder build.

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:org.openscore.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset());
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }//from ww w .  java 2 s. c  o  m
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        Charset charset = contentType != null ? contentType.getCharset() : null;
        httpEntity = new UrlEncodedFormEntity(list, charset);
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*from www .  j av  a  2 s  .  c o  m*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:org.wso2.ml.client.MLClient.java

public CloseableHttpResponse createdDataSet(JSONObject datasetConf) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(mlHost + "/api/datasets/");
    httpPost.setHeader(MLConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addPart("description",
            new StringBody(datasetConf.get("description").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("sourceType",
            new StringBody(datasetConf.get("sourceType").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("destination",
            new StringBody(datasetConf.get("destination").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("dataFormat",
            new StringBody(datasetConf.get("dataFormat").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("containsHeader",
            new StringBody(datasetConf.get("containsHeader").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("datasetName",
            new StringBody(datasetConf.get("datasetName").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("version",
            new StringBody(datasetConf.get("version").toString(), ContentType.TEXT_PLAIN));

    File file = new File(mlDatasetPath);
    multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
            datasetConf.get("file").toString());

    httpPost.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(httpPost);

}

From source file:com.nc.common.utils.HttpUtils.java

/**
 * <pre>/*from ww w  .  jav a 2 s  . c  om*/
 * 1.  : http  
 * 2.  : OpenAPI Multipart 
 * </pre>
 *
 * @method Name : execOpenAPIMultipart
 * @param String subUrl, Map<String, Object> paramMap
 * @return String
 * @throws Exception
 * 
 */
public String execOpenAPIMultipart(String subUrl, Map<String, Object> paramMap) throws Exception {
    String result = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        HttpPost httpPost = new HttpPost(new URI(serverOpenAPI + subUrl));
        // httpPost.addHeader("Content-Type", "application/json");

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .setCharset(Charset.forName(CommonConstants.DEFAULT_CHARSET));

        Iterator<String> iter = paramMap.keySet().iterator();
        String key = null;
        String val = null;

        while (iter.hasNext()) {
            key = iter.next();
            val = (String) paramMap.get(key);

            if (log.isDebugEnabled()) {
                log.debug(
                        "==========================================================================================");
                log.debug(" = ? : [{} - {}] =", key, val);
                log.debug(
                        "==========================================================================================");
            }

            multipartEntityBuilder.addTextBody(key, val);
        }
        httpPost.setEntity(multipartEntityBuilder.build());

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API   : [{}]", httpPost);
            log.debug(
                    "==========================================================================================");
        }

        CloseableHttpResponse response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();

        if (log.isDebugEnabled()) {
            log.debug(
                    "==========================================================================================");
            log.debug("= API  ? : [{}]", statusLine);
            log.debug(
                    "==========================================================================================");
        }

        try {
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity, CommonConstants.DEFAULT_CHARSET);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "==========================================================================================");
                        log.debug("= API    : [{}] =", result);
                        log.debug(
                                "==========================================================================================");
                    }
                }
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Creates an <tt>HttpMethod</tt> instance according to the specified parameters.
 * @param webRequest the request// www.j  a  va2 s.co  m
 * @param httpClientBuilder the httpClientBuilder that will be configured
 * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters
 * @throws IOException
 * @throws URISyntaxException
 */
@SuppressWarnings("deprecation")
private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder)
        throws IOException, URISyntaxException {

    final String charset = webRequest.getCharset();

    // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request
    // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're
    // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode
    // chars in the URL.
    final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset);

    // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path
    // what shouldn't happen here
    URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(),
            escapeQuery(url.getQuery()), null);
    if (getVirtualHost() != null) {
        uri = URI.create(getVirtualHost());
    }
    final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri);
    setProxy(httpMethod, webRequest);
    if (!(httpMethod instanceof HttpEntityEnclosingRequest)) {
        // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD
        if (!webRequest.getRequestParameters().isEmpty()) {
            final List<NameValuePair> pairs = webRequest.getRequestParameters();
            final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
            final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
            uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query,
                    null);
            httpMethod.setURI(uri);
        }
    } else { // POST as well as PUT and PATCH
        final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod;

        if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) {
            final HttpPost postMethod = (HttpPost) method;
            if (webRequest.getRequestBody() == null) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                final StringEntity urlEncodedEntity = new StringEntity(query, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            } else {
                final String body = StringUtils.defaultString(webRequest.getRequestBody());
                final StringEntity urlEncodedEntity = new StringEntity(body, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            }
        } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) {
            final Charset c = getCharset(charset, webRequest.getRequestParameters());
            final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode();
            builder.setCharset(c);

            for (final NameValuePair pair : webRequest.getRequestParameters()) {
                if (pair instanceof KeyDataPair) {
                    buildFilePart((KeyDataPair) pair, builder);
                } else {
                    builder.addTextBody(pair.getName(), pair.getValue(),
                            ContentType.create("text/plain", charset));
                }
            }
            method.setEntity(builder.build());
        } else { // for instance a PUT or PATCH request
            final String body = webRequest.getRequestBody();
            if (body != null) {
                method.setEntity(new StringEntity(body, charset));
            }
        }
    }

    configureHttpProcessorBuilder(httpClientBuilder, webRequest);

    // Tell the client where to get its credentials from
    // (it may have changed on the webClient since last call to getHttpClientFor(...))
    final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider();

    // if the used url contains credentials, we have to add this
    final Credentials requestUrlCredentials = webRequest.getUrlCredentials();
    if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestUrlCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }

    // if someone has set credentials to this request, we have to add this
    final Credentials requestCredentials = webRequest.getCredentials();
    if (null != requestCredentials) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER);

    return httpMethod;
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

/**
 * This method is use to post data in multidata format
 * @param url//from  w w w .  ja  va  2s  .  c om
 *          - backend url
 * @param mobileApplicationBean
 *          - Bean class of the mobile application
 * @param headers
 *          - header files
 */
public static String doPostMultiData(String url, MobileApplicationBean mobileApplicationBean,
        Map<String, String> headers) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    // initializing headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            httpPost.setHeader(key, headers.get(key));
        }
    }
    MultipartEntityBuilder reqEntity;
    reqEntity = MultipartEntityBuilder.create();
    reqEntity.addPart("version",
            new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("provider",
            new StringBody(mobileApplicationBean.getProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("markettype",
            new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("platform",
            new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("description",
            new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA));
    FileBody bannerImageFile = new FileBody(mobileApplicationBean.getBannerFilePath());
    reqEntity.addPart("bannerFile", bannerImageFile);
    FileBody iconImageFile = new FileBody(mobileApplicationBean.getIconFile());
    reqEntity.addPart("iconFile", iconImageFile);
    FileBody screenShot1 = new FileBody(mobileApplicationBean.getScreenShot1File());
    reqEntity.addPart("screenshot1File", screenShot1);
    FileBody screenShot2 = new FileBody(mobileApplicationBean.getScreenShot2File());
    reqEntity.addPart("screenshot2File", screenShot2);
    FileBody screenShot3 = new FileBody(mobileApplicationBean.getScreenShot3File());
    reqEntity.addPart("screenshot3File", screenShot3);
    reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("mobileapp",
            new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("sso_ssoProvider",
            new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA));
    reqEntity.addPart("appmeta",
            new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA));

    final HttpEntity entity = reqEntity.build();
    httpPost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = "";
    try {
        responseBody = httpClient.execute(httpPost, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseBody;
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormParamWithMultipart() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/formParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();//from   www  .j  a  v  a  2  s.  c  o m
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormDataParamWithSimpleRequest() throws IOException, URISyntaxException {
    // Send x-form-url-encoded request
    HttpURLConnection connection = request("/test/v1/formDataParam", HttpMethod.POST);
    String rawData = "name=wso2&age=10";
    ByteBuffer encodedData = Charset.defaultCharset().encode(rawData);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length));
    try (OutputStream os = connection.getOutputStream()) {
        os.write(Arrays.copyOf(encodedData.array(), encodedData.limit()));
    }/*  ww w  .j  a  v a  2 s .  c o m*/

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");

    // Send multipart/form-data request
    connection = request("/test/v1/formDataParam", HttpMethod.POST);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart("name", new StringBody("wso2", ContentType.TEXT_PLAIN));
    builder.addPart("age", new StringBody("10", ContentType.TEXT_PLAIN));
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    inputStream = connection.getInputStream();
    response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "wso2:10");
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;//from  ww w  .ja va 2 s.c  om
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add xml part to the multipart entity
    if (xml != null) {
        //InputStreamBody xmlPart = new InputStreamBody(
        //  new ByteArrayInputStream( xml.getBytes( getEncoding() ) ),
        //  ContentType.parse( "application/xml" ),
        //  "body.xml" );
        //b.addPart( "metadata", xmlPart );
        b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        mimeType = StringUtils.trimToNull(mimeType);
        if (mimeType == null)
            mimeType = "application/octet-stream";

        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";

        //InputStreamBody filePart = new InputStreamBody(
        //  input, ContentType.create( mimeType ), fileName );
        //b.addPart( "attachment", filePart );
        b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept", "application/xml");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

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 {/*from  w  w  w. j  ava2 s .c o m*/
        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();
        }
    }
}