Example usage for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE

List of usage examples for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE

Introduction

In this page you can find the example usage for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE.

Prototype

String USE_EXPECT_CONTINUE

To view the source code for org.apache.http.params CoreProtocolPNames USE_EXPECT_CONTINUE.

Click Source Link

Usage

From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {// ww w  .  j a  v  a 2 s.c om
        HttpRequestBase commonsRequest;

        final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String url_string = req.getURL();
        final URI url_orig;
        try {
            url_orig = new URI(url_string);
        } catch (final URISyntaxException e) {
            throw new TwitterException(e);
        }
        final String host = url_orig.getHost(), authority = url_orig.getAuthority();
        final String resolved_host = resolver != null ? resolver.resolve(host) : null;
        final String resolved_url = !isEmpty(resolved_host)
                ? url_string.replace("://" + host, "://" + resolved_host)
                : url_string;

        if (req.getMethod() == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolved_url);
        } else if (req.getMethod() == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolved_url);
            // parameter has a file?
            boolean hasFile = false;
            final HttpParameter[] params = req.getParameters();
            if (params != null) {
                for (final HttpParameter parameter : params) {
                    if (parameter.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    if (params.length > 0) {
                        post.setEntity(new UrlEncodedFormEntity(params));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter parameter : params) {
                        if (parameter.isFile()) {
                            final ContentBody body = new FileBody(parameter.getFile(),
                                    parameter.getContentType());
                            me.addPart(parameter.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(parameter.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(parameter.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (req.getMethod() == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolved_url);
        } else if (req.getMethod() == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolved_url);
        } else if (req.getMethod() == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolved_url);
        } else
            throw new TwitterException("Unsupported request method " + req.getMethod());
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        String authorizationHeader;
        if (req.getAuthorization() != null
                && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        if (!isEmpty(resolved_host) && !resolved_host.equals(host)) {
            commonsRequest.addHeader("Host", authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java

@Override
public twitter4j.internal.http.HttpResponse request(final twitter4j.internal.http.HttpRequest req)
        throws TwitterException {
    try {/*ww w  .jav a 2  s.  c  o  m*/
        HttpRequestBase commonsRequest;

        //final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String url_string = req.getURL();
        final URL url_orig = new URL(url_string);
        final String host = url_orig.getHost();
        //final String resolved_host = resolver != null ? resolver.resolve(host) : null;
        //final String resolved_url = resolved_host != null ? url_string.replace("://" + host, "://" + resolved_host)
        //      : url_string;
        final String resolved_url = url_string;
        if (req.getMethod() == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolved_url);
        } else if (req.getMethod() == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolved_url);
            // parameter has a file?
            boolean hasFile = false;
            if (req.getParameters() != null) {
                for (final HttpParameter parameter : req.getParameters()) {
                    if (parameter.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    final ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
                    for (final HttpParameter parameter : req.getParameters()) {
                        args.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
                    }
                    if (args.size() > 0) {
                        post.setEntity(new UrlEncodedFormEntity(args, "UTF-8"));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter parameter : req.getParameters()) {
                        if (parameter.isFile()) {
                            final ContentBody body = new FileBody(parameter.getFile(),
                                    parameter.getContentType());
                            me.addPart(parameter.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(parameter.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(parameter.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (req.getMethod() == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolved_url);
        } else if (req.getMethod() == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolved_url);
        } else if (req.getMethod() == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolved_url);
        } else
            throw new AssertionError();
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        String authorizationHeader;
        if (req.getAuthorization() != null
                && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        //if (resolved_host != null && !host.equals(resolved_host)) {
        //commonsRequest.addHeader("Host", host);
        //}
        final ApacheHttpClientHttpResponseImpl res = new ApacheHttpClientHttpResponseImpl(
                client.execute(commonsRequest), conf);
        final int statusCode = res.getStatusCode();
        if (statusCode < OK && statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java

@Override
public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException {
    try {/* w  w w  . j  a  va 2s . c o m*/
        HttpRequestBase commonsRequest;

        final HostAddressResolver resolver = conf.getHostAddressResolver();
        final String urlString = req.getURL();
        final URI urlOrig;
        try {
            urlOrig = new URI(urlString);
        } catch (final URISyntaxException e) {
            throw new TwitterException(e);
        }
        final String host = urlOrig.getHost(), authority = urlOrig.getAuthority();
        final String resolvedHost = resolver != null ? resolver.resolve(host) : null;
        final String resolvedUrl = !isEmpty(resolvedHost)
                ? urlString.replace("://" + host, "://" + resolvedHost)
                : urlString;

        final RequestMethod method = req.getMethod();
        if (method == RequestMethod.GET) {
            commonsRequest = new HttpGet(resolvedUrl);
        } else if (method == RequestMethod.POST) {
            final HttpPost post = new HttpPost(resolvedUrl);
            // parameter has a file?
            boolean hasFile = false;
            final HttpParameter[] params = req.getParameters();
            if (params != null) {
                for (final HttpParameter param : params) {
                    if (param.isFile()) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    if (params.length > 0) {
                        post.setEntity(new UrlEncodedFormEntity(params));
                    }
                } else {
                    final MultipartEntity me = new MultipartEntity();
                    for (final HttpParameter param : params) {
                        if (param.isFile()) {
                            final ContentBody body;
                            if (param.getFile() != null) {
                                body = new FileBody(param.getFile(), param.getContentType());
                            } else {
                                body = new InputStreamBody(param.getFileBody(), param.getFileName(),
                                        param.getContentType());
                            }
                            me.addPart(param.getName(), body);
                        } else {
                            final ContentBody body = new StringBody(param.getValue(),
                                    "text/plain; charset=UTF-8", Charset.forName("UTF-8"));
                            me.addPart(param.getName(), body);
                        }
                    }
                    post.setEntity(me);
                }
            }
            post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
            commonsRequest = post;
        } else if (method == RequestMethod.DELETE) {
            commonsRequest = new HttpDelete(resolvedUrl);
        } else if (method == RequestMethod.HEAD) {
            commonsRequest = new HttpHead(resolvedUrl);
        } else if (method == RequestMethod.PUT) {
            commonsRequest = new HttpPut(resolvedUrl);
        } else
            throw new TwitterException("Unsupported request method " + method);
        final Map<String, String> headers = req.getRequestHeaders();
        for (final String headerName : headers.keySet()) {
            commonsRequest.addHeader(headerName, headers.get(headerName));
        }
        final Authorization authorization = req.getAuthorization();
        final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req)
                : null;
        if (authorizationHeader != null) {
            commonsRequest.addHeader("Authorization", authorizationHeader);
        }
        if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) {
            commonsRequest.addHeader("Host", authority);
        }

        final ApacheHttpClientHttpResponseImpl res;
        try {
            res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf);
        } catch (final IllegalStateException e) {
            throw new TwitterException("Please check your API settings.", e);
        } catch (final NullPointerException e) {
            // Bug http://code.google.com/p/android/issues/detail?id=5255
            throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e);
        } catch (final OutOfMemoryError e) {
            // I don't know why OOM thown, but it should be catched.
            System.gc();
            throw new TwitterException("Unknown error", e);
        }
        final int statusCode = res.getStatusCode();
        if (statusCode < OK || statusCode > ACCEPTED)
            throw new TwitterException(res.asString(), req, res);
        return res;
    } catch (final IOException e) {
        throw new TwitterException(e);
    }
}

From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java

@Test(dependsOnGroups = { "glassfish-osgi-startup" })
public void testWebAvailability() throws NoSuchAlgorithmException, KeyManagementException, IOException {
    logTest();//from www .j a va2 s  . c om

    DefaultHttpClient http = getHTTPClient();
    try {
        HttpGet httpget = new HttpGet("http://[::1]/movie/dummy/");
        httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only
        httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

        HttpResponse res = http.execute(httpget);

        if (res.getStatusLine().getStatusCode() == 200) {
            fail("Gained access to secured page at '" + httpget.getURI().toASCIIString() + "' [status="
                    + res.getStatusLine().getStatusCode() + "]");
        }

        log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]",
                new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() });

        HttpGet httpsget = new HttpGet("https://[::1]/movie/dummy/");
        httpsget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only
        httpsget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

        res = http.execute(httpsget);

        if (res.getStatusLine().getStatusCode() == 200) {
            fail("Gained access to secured page at '" + httpsget.getURI().toASCIIString() + "' [status="
                    + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase());
        }

        log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]",
                new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() });

        http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181),
                new UsernamePasswordCredentials("fail", "fail"));

        res = http.execute(httpsget);

        if (res.getStatusLine().getStatusCode() == 200) {
            fail("Gained access with invalid user role to secured page at '" + httpsget.getURI().toASCIIString()
                    + "' [status=" + res.getStatusLine().getStatusCode() + "] "
                    + res.getStatusLine().getReasonPhrase());
        }

        log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]",
                new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() });

        http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181),
                new UsernamePasswordCredentials("test", "test"));

        res = http.execute(httpsget);

        if (res.getStatusLine().getStatusCode() != 200) {
            fail("Failed to access " + httpsget.getURI().toASCIIString() + ": [status="
                    + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase());
        }

        log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]",
                new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() });
    } finally {
        http.getConnectionManager().shutdown();
    }
}

From source file:com.duokan.reader.domain.account.oauth.evernote.TEvernoteHttpClient.java

public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();

    HttpEntity httpEntity = null;/*from   ww  w.  j  av  a 2s  . c  o m*/

    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url_.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders_ != null) {
            for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer_.getInputStream(),
                requestBuffer_.getSize());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        DefaultHttpClient dHTTP = getHTTPClient();
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer_.reset();
        inputStream_ = response.getEntity().getContent();
    } catch (IOException iox) {
        throw new TTransportException(iox);
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer_.reset();
        } catch (IOException e) {
        }
        this.request = null;
    }
}

From source file:com.evernote.client.conn.mobile.TEvernoteHttpClient.java

@Deprecated
public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();

    HttpEntity httpEntity;//from w w  w .j a v a 2 s.com

    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders != null) {
            for (Map.Entry<String, String> header : customHeaders.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer.getInputStream(),
                requestBuffer.getBytesWritten());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        DefaultHttpClient dHTTP = getHTTPClient();
        //noinspection ConstantConditions
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer.reset();
        inputStream = response.getEntity().getContent();
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer.reset();
        } catch (IOException ignored) {
        }
        this.request = null;
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcap2Adapter.java

/**
 * @inheritDoc/*  ww w.  j  a  v a 2s  .  c  o m*/
 */
public void writeObjectFromStream(final String targetNode, final String targetPath, final InputStream is,
        final FileMetadata ingestionMetadata) throws StorageAdapterException {
    HttpHost httpHost = new HttpHost(targetNode, profile.getPort(), profile.getProtocol());
    String filePath = targetPath;

    if (!filePath.startsWith(HttpGatewayConstants.METADATA_MOUNT_URL_DIR)) {
        filePath = getProfile().resolvePath(filePath);
    }

    String queryString = null;
    if (ingestionMetadata != null) {
        queryString = generateQueryParameters(ingestionMetadata, false);
    }

    URI uri = null;
    try {
        uri = URIUtils.createURI(profile.getProtocol(), targetNode, profile.getPort(), filePath, queryString,
                null);
    } catch (URISyntaxException e) {
        LOG.log(Level.WARNING, "Unexpected error generating put URI for : " + targetPath);
        throw new StorageAdapterLiteralException("Error writing object to the server", e);
    }
    HttpPut request = new HttpPut(uri);

    InputStreamEntity isEntity = new InputStreamEntity(is, -1);
    request.setEntity(isEntity);

    request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);
    request.getParams().setParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 100);

    // Eventually we will just return this cookie which will be passed back to the caller.
    HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost);
    synchronized (savingCookieLock) {
        if (savedCookie != null) {
            throw new RuntimeException(
                    "This adapter already has a current connection to host -- cannot create two at once.");
        }
        savedCookie = cookie;
    }
    try {
        executeMethod(cookie);
        this.handleHttpResponse(cookie.getResponse(), "writing", targetPath);
    } catch (IOException e) {
        this.handleIOExceptionFromRequest(e, "writing", targetPath);
    } finally {
        close();
    }
}

From source file:com.ichi2.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;// w  ww  .  j  a v a 2  s  .c  om
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:com.evernote.android.edam.TAndroidHttpClient.java

public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();

    LOGGER.info((Thread.currentThread().getId()) + ": Creating thrift request");
    HttpEntity httpEntity = null;/*w  w w .  j  a v a2 s  .  com*/

    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url_.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders_ != null) {
            for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer_.getInputStream(),
                requestBuffer_.getSize());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        DefaultHttpClient dHTTP = getHTTPClient();
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer_.reset();
        inputStream_ = response.getEntity().getContent();
    } catch (IOException iox) {
        throw new TTransportException(iox);
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer_.reset();
        } catch (IOException e) {
        }
        LOGGER.info((Thread.currentThread().getId()) + ": Response received in: "
                + (System.currentTimeMillis() - timer) + "ms");
        this.request = null;
    }
}