Example usage for org.apache.http.params HttpProtocolParams setUseExpectContinue

List of usage examples for org.apache.http.params HttpProtocolParams setUseExpectContinue

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setUseExpectContinue.

Prototype

public static void setUseExpectContinue(HttpParams httpParams, boolean z) 

Source Link

Usage

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];/*from   w  ww  .  j a  v a  2  s  .  co  m*/
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }/*from  ww w . j  av  a2  s  . c om*/
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:org.medcare.Dicom.DicomActivity.java

public ImageController getRemoteImage(final URL aURL) {

    HttpGet httpget = new HttpGet(aURL.toExternalForm());
    try {/* w  ww .j  ava2 s .  c om*/

        /*Modif pour SFR
                 Log.e(TAG, "OPENCONNECTION!!!!!!!!!!!!!!!");
                 final URLConnection conn = aURL.openConnection();
                 // conn.setRequestProperty("User-Agent",
                 // "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
                 conn.setRequestProperty("User-Agent",
                       "Mozilla/5.0 (Linux; U; Windows NT 6.1; en-us; dream");
                 Log.e(TAG, "CONNECT!!!!!!!!!!!!!!!");
                
                 conn.connect();
                 Log.e(TAG, "INPUTSTREAM!!!!!!!!!!!!!!!");
                
                 final BufferedInputStream bin = new BufferedInputStream(conn
                       .getInputStream());
        //Log.e(TAG, "Response code is " + conn.getResponseCode());
        */
        if (httpClient == null) {
            this.httpClient = new DefaultHttpClient();
        }
        Log.e(TAG, "AFTER OPENCONNECTION!!!!!!!!!!!!!!!");
        final HttpParams params = httpClient.getParams();
        //HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        //httpget.setHeader("User-Agent", "Mozilla/5.0 (Linux; U; Windows NT 6.1; en-us; dream");
        //httpget.setHeader("User-Agent", USER_AGENT);
        //httpget.addHeader("Authorization", "Basic " + getCredentials());
        //LIGNE pour SFR
        HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
        HttpResponse httpResponse = httpClient.execute(httpget);
        final BufferedInputStream bin = new BufferedInputStream(httpResponse.getEntity().getContent());
        Log.e(TAG, "IMAGEDICOM!!!!!!!!!!!!!!!");
        ImageDicom imageDicom = new ImageDicom();
        try {
            Log.e(TAG, "IMAGEDICOM READ!!!!!!!!!!!!!!!");
            imageDicom.read(bin);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IMAGEDICOM READ EXCEPTION !!!!!!!!!!!!!!!");
            e.printStackTrace();
        }
        // final Bitmap bm = BitmapFactory.decodeStream(bis);
        bin.close();
        return initImageController(imageDicom);
    } catch (Exception e) {
        Log.e(TAG, "OPENCONNECTION ERROR!!!!!!!!!..." + e.getMessage());
        try {
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();
            }
        } catch (Exception e1) {
            Log.e(TAG, "OPENCONNECTION EXCEPTION ERROR!!!!!!!!!..." + e1.getMessage());
        }
        httpClient = null;
    }
    return null;
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

/**
 * Get an HttpConnection object. Will create a new one if needed.
 * //  w  w  w  .  j  a  v a  2 s.c o  m
 * @return A defualt HTTP connection object
 */
private HttpClient getConnection() {
    if (mHttpClient == null) {
        // registers schemes for both http and https
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_OPS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_OPS);
        ConnManagerParams.setTimeout(params, TIMEOUT_OPS);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        if (!mNoCertValidation)
            registry.register(new Scheme("https", sslSocketFactory, 443));
        else
            registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        mHttpClient = new DefaultHttpClient(manager, params);

    }
    return mHttpClient;
}

From source file:com.snaptic.api.SnapticAPI.java

private HttpResponse performPOST(String method, List<NameValuePair> parameters, Part[] parts) {
    HttpPost httppost = new HttpPost(SNAPTIC_BASE_URL + method);
    httppost.addHeader("Authorization", basicUserAuth);

    if (parameters != null && !parameters.isEmpty()) {
        try {//from  ww  w.jav a  2  s.  co  m
            httppost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log("caught UnsupportedEncodingException performing POST " + httppost.getURI());
            e.printStackTrace();
            return null;
        }
    } else if (parts != null) {
        HttpProtocolParams.setUseExpectContinue(httppost.getParams(), false);
        httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
    }

    HttpResponse response = null;

    try {
        response = httpClient.execute(httppost);
    } catch (ClientProtocolException e) {
        log("caught ClientProtocolException performing POST " + httppost.getURI());
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        log("caught IOException performing POST " + httppost.getURI());
        e.printStackTrace();
        return null;
    }

    sync_trace("POST " + httppost.getURI() + " returned " + response.getStatusLine().getStatusCode() + ' '
            + response.getStatusLine().getReasonPhrase());
    return response;
}

From source file:com.mhise.util.MHISEUtil.java

public static String CallWebService(String url, String soapAction, String envelope,
        DefaultHttpClient httpClient) {//from  w w  w . j a v  a2s . c om
    // request parameters
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 60000);
    HttpConnectionParams.setSoTimeout(params, 60000);
    // set parameter
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
    // POST the envelope
    HttpPost httppost = new HttpPost(url);

    // add headers
    httppost.setHeader("action", soapAction);
    httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8;");
    String responseString = "";
    try {
        // the entity holds the request
        HttpEntity entity = new StringEntity(envelope);
        httppost.setEntity(entity);

        // Response handler
        ResponseHandler<String> rh = new ResponseHandler<String>() {
            // invoked when client receives response
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {

                //Log.e("CallWebService",getResponseBody(response));

                // get response entity
                HttpEntity entity = response.getEntity();

                // read the response as byte array
                StringBuffer out = new StringBuffer();

                byte[] b = EntityUtils.toByteArray(entity);
                String str = new String(b, 0, b.length);
                Log.e("string length", "" + str);
                //int index = b.length-1;
                //Log.e("b lase string",""+(char)(b[index-2])+(char)(b[index-1])+(char)(b[index]));
                // write the response byte array to a string buffer

                out.append(new String(b, 0, b.length));

                return out.toString();
                //return getResponseBody(response);
            }
        };
        try {
            responseString = httpClient.execute(httppost, rh);

        } catch (Exception e) {
            Logger.debug("MHISEUtil-->CallWebService -->", "finally clause");
        }
    } catch (Exception e) {
        Logger.debug("MHISEUtil-->CallWebService -->", "finally clause");
    }

    // close the connection
    httpClient.getConnectionManager().closeExpiredConnections();
    httpClient.getConnectionManager().shutdown();
    Log.e("Response", "" + responseString);
    return responseString;
}

From source file:com.pk.wallpapermanager.PkWallpaperManager.java

/**
 * Initializes our handy little client for cloud calls.
 * Don't modify this unless you know what you're doing.
 *//*w  w w.j a  v a  2  s  . c  o  m*/
private void initHttpClient() {
    // Basic HTTP parameters & manager set up
    HttpParams parameters = new BasicHttpParams();
    HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(parameters, false);
    HttpConnectionParams.setTcpNoDelay(parameters, true);
    HttpConnectionParams.setSocketBufferSize(parameters, 8192);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);

    // Finally, initialize our client with these parameters and manager
    this.httpClient = new DefaultHttpClient(tsccm, parameters);
}

From source file:com.heaptrip.util.http.bixo.fetcher.SimpleHttpFetcher.java

private synchronized void init() {
    if (_httpClient == null) {
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();

        // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager)
        // cm.setMaxTotalConnections(_maxThreads);
        // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10));
        ConnManagerParams.setMaxTotalConnections(params, _maxThreads);

        // Set the maximum time we'll wait for a spare connection in the
        // connection pool. We
        // shouldn't actually hit this, as we make sure (in FetcherManager) that
        // the max number
        // of active requests doesn't exceed the value returned by getMaxThreads()
        // here./*w ww  . j  av  a  2 s  .c om*/
        ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT);

        // Set the socket and connection timeout to be something reasonable.
        HttpConnectionParams.setSoTimeout(params, _socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout);

        // Even with stale checking enabled, a connection can "go stale" between
        // the check and the
        // next request. So we still need to handle the case of a closed socket
        // (from the server side),
        // and disabling this check improves performance.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // FUTURE - set this on a per-route (host) basis when we have per-host
        // policies for
        // doing partner crawls. We could define a BixoConnPerRoute class that
        // supports this.
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost());
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

        HttpProtocolParams.setVersion(params, _httpVersion);
        HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString());
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);

        // TODO KKr - set on connection manager params, or client params?
        CookieSpecParamBean cookieParams = new CookieSpecParamBean(params);
        cookieParams.setSingleHeader(true);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sf = null;

        if (sf != null) {
            sf.setHostnameVerifier(new DummyX509HostnameVerifier());
            schemeRegistry.register(new Scheme("https", sf, 443));
        } else {
            LOGGER.warn("No valid SSLContext found for https");
        }

        // Use ThreadSafeClientConnManager since more than one thread will be
        // using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        _httpClient = new DefaultHttpClient(cm, params);
        _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
        _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode()));
        _httpClient.addRequestInterceptor(new MyRequestInterceptor());

        params = _httpClient.getParams();
        // FUTURE KKr - support authentication
        HttpClientParams.setAuthenticating(params, false);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        ClientParamBean clientParams = new ClientParamBean(params);
        if (_fetcherPolicy.getMaxRedirects() == 0) {
            clientParams.setHandleRedirects(false);
        } else {
            clientParams.setHandleRedirects(true);
            clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects());
        }

        // Set up default headers. This helps us get back from servers what we
        // want.
        HashSet<Header> defaultHeaders = new HashSet<Header>();
        defaultHeaders
                .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage()));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT));

        clientParams.setDefaultHeaders(defaultHeaders);
    }
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * Creates default params setting the user agent.
 * /*w w w. j  ava2  s.  com*/
 * @return Basic HTTP parameters with a custom user agent
 */
protected HttpParams createDefaultHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    String version = Version.getSpecification();
    if (version == null) {
        version = VersionInfo.UNAVAILABLE;
    }
    HttpProtocolParams.setUserAgent(params, "Sardine/" + version);
    // Only selectively enable this for PUT but not all entity enclosing
    // methods
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    return params;
}

From source file:bixo.fetcher.SimpleHttpFetcher.java

private synchronized void init() {
    if (_httpClient == null) {
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();

        // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager)
        // cm.setMaxTotalConnections(_maxThreads);
        // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10));
        ConnManagerParams.setMaxTotalConnections(params, _maxThreads);

        // Set the maximum time we'll wait for a spare connection in the
        // connection pool. We
        // shouldn't actually hit this, as we make sure (in FetcherManager) that
        // the max number
        // of active requests doesn't exceed the value returned by getMaxThreads()
        // here.//from  www . ja  v  a2s .  c om
        ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT);

        // Set the socket and connection timeout to be something reasonable.
        HttpConnectionParams.setSoTimeout(params, _socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout);

        // Even with stale checking enabled, a connection can "go stale" between
        // the check and the
        // next request. So we still need to handle the case of a closed socket
        // (from the server side),
        // and disabling this check improves performance.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        // FUTURE - set this on a per-route (host) basis when we have per-host
        // policies for
        // doing partner crawls. We could define a BixoConnPerRoute class that
        // supports this.
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost());
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

        HttpProtocolParams.setVersion(params, _httpVersion);
        HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString());
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);

        // TODO KKr - set on connection manager params, or client params?
        CookieSpecParamBean cookieParams = new CookieSpecParamBean(params);
        cookieParams.setSingleHeader(true);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SSLSocketFactory sf = null;

        for (String contextName : SSL_CONTEXT_NAMES) {
            try {
                SSLContext sslContext = SSLContext.getInstance(contextName);
                sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
                sf = new SSLSocketFactory(sslContext);
                break;
            } catch (NoSuchAlgorithmException e) {
                LOGGER.debug("SSLContext algorithm not available: " + contextName);
            } catch (Exception e) {
                LOGGER.debug("SSLContext can't be initialized: " + contextName, e);
            }
        }

        if (sf != null) {
            sf.setHostnameVerifier(new DummyX509HostnameVerifier());
            schemeRegistry.register(new Scheme("https", sf, 443));
        } else {
            LOGGER.warn("No valid SSLContext found for https");
        }

        // Use ThreadSafeClientConnManager since more than one thread will be
        // using the HttpClient.
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        _httpClient = new DefaultHttpClient(cm, params);
        _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
        _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode()));
        _httpClient.addRequestInterceptor(new MyRequestInterceptor());

        params = _httpClient.getParams();
        // FUTURE KKr - support authentication
        HttpClientParams.setAuthenticating(params, false);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        ClientParamBean clientParams = new ClientParamBean(params);
        if (_fetcherPolicy.getMaxRedirects() == 0) {
            clientParams.setHandleRedirects(false);
        } else {
            clientParams.setHandleRedirects(true);
            clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects());
        }

        // Set up default headers. This helps us get back from servers what we
        // want.
        HashSet<Header> defaultHeaders = new HashSet<Header>();
        defaultHeaders
                .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage()));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
        defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT));

        clientParams.setDefaultHeaders(defaultHeaders);
    }
}