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

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

Introduction

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

Prototype

String PROTOCOL_VERSION

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

Click Source Link

Usage

From source file:org.doctester.testbrowser.TestBrowserImpl.java

private Response makePostOrPutRequest(Request httpRequest) {

    org.apache.http.HttpResponse apacheHttpClientResponse;
    Response response = null;/*from   w w  w  .  j  a v  a  2 s . c  om*/

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpEntityEnclosingRequestBase apacheHttpRequest;

        if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPost(httpRequest.uri);

        } else {

            apacheHttpRequest = new HttpPut(httpRequest.uri);
        }

        if (httpRequest.headers != null) {
            // add all headers
            for (Entry<String, String> header : httpRequest.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        ///////////////////////////////////////////////////////////////////
        // Either add form parameters...
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.formParameters != null) {

            List<BasicNameValuePair> formparams = Lists.newArrayList();
            for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) {

                formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
            }

            // encode form parameters and add
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add multipart file upload
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.filesToUpload != null) {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) {

                // For File parameters
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));

            }

            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add payload and convert if Json or Xml
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.payload != null) {

            if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) {

                String string = new ObjectMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType("application/json; charset=utf-8");

                apacheHttpRequest.setEntity(entity);

            } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) {

                String string = new XmlMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8);

                apacheHttpRequest.setEntity(new StringEntity(string, "utf-8"));

            } else if (httpRequest.payload instanceof String) {

                StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8");
                apacheHttpRequest.setEntity(entity);

            } else {

                StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8");
                apacheHttpRequest.setEntity(entity);

            }

        }

        setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects);

        // Here we go!
        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);
        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        apacheHttpRequest.releaseConnection();

    } catch (IOException e) {
        logger.error("Fatal problem creating POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:de.azapps.mirakel.sync.Network.java

private String downloadUrl(String myurl) throws IOException, URISyntaxException {
    if (token != null) {
        myurl += "?authentication_key=" + token;
    }/*from w  w  w. jav a 2  s.  c  om*/
    if (myurl.indexOf("https") == -1) {
        Integer[] t = { NoHTTPS };
        publishProgress(t);
    }

    /*
     * String authorizationString = null;
     * if (syncTyp == ACCOUNT_TYPES.CALDAV) {
     * authorizationString = "Basic "
     * + Base64.encodeToString(
     * (username + ":" + password).getBytes(),
     * Base64.NO_WRAP);
     * }
     */

    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(new AuthScope(new URI(myurl).getHost(), -1),
            new UsernamePasswordCredentials(username, password));

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClient httpClient;
    /*
     * if(syncTyp == ACCOUNT_TYPES.MIRAKEL)
     * httpClient = sslClient(client);
     * else {
     */
    DefaultHttpClient tmpHttpClient = new DefaultHttpClient(params);
    tmpHttpClient.setCredentialsProvider(credentials);

    httpClient = tmpHttpClient;
    // }
    httpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);

    HttpResponse response;
    try {
        switch (mode) {
        case GET:
            Log.v(TAG, "GET " + myurl);
            HttpGet get = new HttpGet();
            get.setURI(new URI(myurl));
            response = httpClient.execute(get);
            break;
        case PUT:
            Log.v(TAG, "PUT " + myurl);
            HttpPut put = new HttpPut();
            if (syncTyp == ACCOUNT_TYPES.CALDAV) {
                put.addHeader(HTTP.CONTENT_TYPE, "text/calendar; charset=utf-8");
            }
            put.setURI(new URI(myurl));
            put.setEntity(new StringEntity(content, HTTP.UTF_8));
            Log.v(TAG, content);

            response = httpClient.execute(put);
            break;
        case POST:
            Log.v(TAG, "POST " + myurl);
            HttpPost post = new HttpPost();
            post.setURI(new URI(myurl));
            post.setEntity(new UrlEncodedFormEntity(headerData, HTTP.UTF_8));
            response = httpClient.execute(post);
            break;
        case DELETE:
            Log.v(TAG, "DELETE " + myurl);
            HttpDelete delete = new HttpDelete();
            delete.setURI(new URI(myurl));
            response = httpClient.execute(delete);
            break;
        case REPORT:
            Log.v(TAG, "REPORT " + myurl);
            HttpReport report = new HttpReport();
            report.setURI(new URI(myurl));
            Log.d(TAG, content);
            report.setEntity(new StringEntity(content, HTTP.UTF_8));
            response = httpClient.execute(report);
            break;
        default:
            Log.wtf("HTTP-MODE", "Unknown Http-Mode");
            return null;
        }
    } catch (Exception e) {
        Log.e(TAG, "No Networkconnection available");
        Log.w(TAG, Log.getStackTraceString(e));
        return "";
    }
    Log.v(TAG, "Http-Status: " + response.getStatusLine().getStatusCode());
    if (response.getEntity() == null)
        return "";
    String r = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
    Log.d(TAG, r);
    return r;
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

private String postMultipartEntity(MultipartEntity entity) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost post = new HttpPost(mWsUrl);
    setUserAgent(post);/* w w w  .j a  v  a 2 s . c  o m*/
    post.setEntity(entity);
    String responseAsString = "";

    try {
        HttpResponse response = client.execute(post);
        Header header = response.getFirstHeader(RESPONSE_HEADER_WEBTRANS_ID);
        if (header == null) {
            HttpEntity responseEntity = response.getEntity();
            responseAsString = EntityUtils.toString(responseEntity, HTTP.UTF_8);
        } else {
            // return the token
            responseAsString = header.getValue();
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
    return responseAsString;
}

From source file:ninja.utils.NinjaTestBrowser.java

public String uploadFile(String url, String paramName, File fileToUpload) {

    String response = null;/*from  w  ww  .ja v  a  2 s  .c  o  m*/

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost post = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        entity.addPart(paramName, new FileBody((File) fileToUpload));

        post.setEntity(entity);

        // Here we go!
        response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        post.releaseConnection();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return response;

}

From source file:org.codegist.crest.io.http.HttpClientFactoryTest.java

@Test
public void createWithMoreThanOneShouldCreateDefaultHttpClientWithConnectionManagerSetup() throws Exception {
    DefaultHttpClient expected = mock(DefaultHttpClient.class);
    ProxySelectorRoutePlanner planner = mock(ProxySelectorRoutePlanner.class);
    ClientConnectionManager clientConnectionManager = mock(ClientConnectionManager.class);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    ProxySelector proxySelector = mock(ProxySelector.class);
    BasicHttpParams httpParams = mock(BasicHttpParams.class);
    ConnPerRouteBean routeBean = mock(ConnPerRouteBean.class);
    PlainSocketFactory plainSocketFactory = mock(PlainSocketFactory.class);
    SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class);
    Scheme plainScheme = new Scheme("http", plainSocketFactory, 80);
    Scheme sslScheme = new Scheme("https", sslSocketFactory, 443);
    ThreadSafeClientConnManager threadSafeClientConnManager = mock(ThreadSafeClientConnManager.class);

    when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
    when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);

    mockStatic(ProxySelector.class);
    when(ProxySelector.getDefault()).thenReturn(proxySelector);

    mockStatic(PlainSocketFactory.class);
    when(PlainSocketFactory.getSocketFactory()).thenReturn(plainSocketFactory);

    mockStatic(SSLSocketFactory.class);
    when(SSLSocketFactory.getSocketFactory()).thenReturn(sslSocketFactory);

    whenNew(SchemeRegistry.class).withNoArguments().thenReturn(schemeRegistry);
    whenNew(Scheme.class).withArguments("http", plainSocketFactory, 80).thenReturn(plainScheme);
    whenNew(Scheme.class).withArguments("https", sslSocketFactory, 443).thenReturn(sslScheme);
    whenNew(ThreadSafeClientConnManager.class).withArguments(httpParams, schemeRegistry)
            .thenReturn(threadSafeClientConnManager);
    whenNew(ConnPerRouteBean.class).withArguments(2).thenReturn(routeBean);
    whenNew(BasicHttpParams.class).withNoArguments().thenReturn(httpParams);
    whenNew(DefaultHttpClient.class).withArguments(threadSafeClientConnManager, httpParams)
            .thenReturn(expected);/*from   w  ww.  j av a  2  s  .  c o m*/
    whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry, proxySelector).thenReturn(planner);

    when(crestConfig.getConcurrencyLevel()).thenReturn(2);
    HttpClient actual = HttpClientFactory.create(crestConfig, getClass());
    assertSame(expected, actual);

    verify(expected).setRoutePlanner(planner);
    verify(httpParams).setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    verify(httpParams).setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, routeBean);
    verify(httpParams).setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 2);
    assertSame(plainScheme, schemeRegistry.getScheme("http"));
    assertSame(sslScheme, schemeRegistry.getScheme("https"));
}

From source file:org.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u/*w  w w .  j  av  a  2s.  co  m*/
 * @param data
 * @param headers
 * @return
 */
public HttpResponseBean postForm(String u, Map<String, Object> data, Map<String, String> headers) {
    if (headers == null)
        headers = new HashMap<String, String>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        for (String h : headers.keySet()) {
            post.setHeader(h, "" + headers.get(h));
        }
        //HttpPost post = new HttpPost(LOGIN_URL);
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        if (data != null) {
            for (String h : data.keySet()) {
                params.add(new BasicNameValuePair(h, (String) data.get(h)));
            }
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8"));
        post.setEntity(urlEncodedFormEntity);
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);

        HttpResponse resp = null;
        try {
            resp = client.execute(host, post, context);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Map<String, String> rh = new HashMap<String, String>();
        for (Header h : resp.getAllHeaders()) {
            rh.put(h.getName(), h.getValue());
        }
        try {
            HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh,
                    EntityUtils.toByteArray(resp.getEntity()));
            printIfError(u, r);
            return r;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToVideoBin(final Activity activity, final Handler handler,
        final String video_absolutepath, final String title, final String description,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doPOSTtoVideoBin starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.

            boolean failed = false;

            HttpClient client = new DefaultHttpClient();

            if (useProxy) {
                HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }/*from   w w w .  j  a  v  a 2  s.c  o  m*/

            client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

            URI url = null;
            try {
                url = new URI(res.getString(R.string.http_videobin_org_add));
            } catch (URISyntaxException e) {
                // Ours is a fixed URL, so not likely to get here.
                e.printStackTrace();
                return;

            }
            HttpPost post = new HttpPost(url);
            CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {
                        int lastPercent = 0;

                        @Override
                        public void transferred(long num) {

                            percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f);
                            //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength);
                            if (lastPercent != percentUploaded) {
                                ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded);
                                lastPercent = percentUploaded;
                            }
                        }

                    });

            File file = new File(video_absolutepath);
            entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file));

            try {
                entity.addPart(res.getString(R.string.video_bin_API_api),
                        new StringBody("1", "text/plain", Charset.forName("UTF-8")));

                // title
                entity.addPart(res.getString(R.string.video_bin_API_title),
                        new StringBody(title, "text/plain", Charset.forName("UTF-8")));

                // description
                entity.addPart(res.getString(R.string.video_bin_API_description),
                        new StringBody(description, "text/plain", Charset.forName("UTF-8")));

            } catch (IllegalCharsetNameException e) {
                // error
                e.printStackTrace();
                failed = true;

            } catch (UnsupportedCharsetException e) {
                // error
                e.printStackTrace();
                return;
            } catch (UnsupportedEncodingException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            post.setEntity(entity);

            totalLength = entity.getContentLength();

            // Here we go!
            String response = null;
            try {
                response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
            } catch (ParseException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (ClientProtocolException e) {
                // error
                e.printStackTrace();
                failed = true;
            } catch (IOException e) {
                // error
                e.printStackTrace();
                failed = true;
            }

            client.getConnectionManager().shutdown();

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((SSCXferActivity) activity).finishedUploading(false);

                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_videobin_org_failed_));
                    }
                }, 0);

                return;
            }

            Log.d(TAG, " video bin got back " + response);

            // XXX Convert to preference for auto-email on videobin post
            // XXX ADD EMAIL NOTIF to all other upload methods
            // stuck on YES here, if email is defined.

            if (emailAddress != null && response != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id,
                    res.getString(R.string.http_videobin_org_add), response, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_));

                }
            }, 0);
        }
    });

    t.start();

    return t;

}

From source file:anhttpclient.impl.DefaultWebBrowser.java

private HttpParams getBasicHttpParams() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    params.setParameter(CoreProtocolPNames.USER_AGENT, WebBrowserConstants.DEFAULT_USER_AGENT);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, clientConnectionFactoryClassName);

    /*Custom parameter to be used in implementation of {@link ClientConnectionManagerFactory}*/
    params.setParameter(ClientConnectionManagerFactoryImpl.THREAD_SAFE_CONNECTION_MANAGER, this.threadSafe);

    return params;
}

From source file:ninja.utils.NinjaTestBrowser.java

public String postJson(String url, Object object) {

    try {/*from www. j  a va 2 s.  com*/
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(new ObjectMapper().writeValueAsString(object), "utf-8");
        entity.setContentType("application/json; charset=utf-8");
        post.setEntity(entity);
        post.releaseConnection();

        // Here we go!
        return EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}