Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.payu.sdk.helper.WebClientDevWrapper.java

/**
 * Wraps a default and secure httpClient
 *
 * @param base the original httpClient//from   w ww .jav  a  2s .  c om
 * @return the hhtpClient wrapped
 * @throws ConnectionException
 */
public static HttpClient wrapClient(HttpClient base) throws ConnectionException {
    try {
        SSLContext ctx = SSLContext.getInstance(Constants.SSL_PROVIDER);

        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        };

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();

        sr.register(new Scheme("https", Constants.HTTPS_PORT, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        throw new ConnectionException("Invalid SSL connection", ex);
    }
}

From source file:org.mulgara.store.jxunit.SparqlQueryJX.java

/**
 * Execute a query against a SPARQL endpoint.
 * @param endpoint The URL of the endpoint.
 * @param query The query to execute./*from   ww  w.j a v a  2 s .c  om*/
 * @param defGraph The default graph to execute the query against,
 *        or <code>null</code> if not set.
 * @return A string representation of the result from the server.
 * @throws IOException If there was an error communicating with the server.
 * @throws UnsupportedEncodingException The SPARQL endpoint used an encoding not understood by this system.
 * @throws HttpClientException An unexpected response was returned from the SPARQL endpoint.
 */
String executeQuery(String endpoint, String query, URI defGraph)
        throws IOException, UnsupportedEncodingException, HttpClientException {
    String request = endpoint + "?";
    if (defGraph != null && (0 != defGraph.toString().length()))
        request += "default-graph-uri=" + defGraph.toString() + "&";
    request += "query=" + URLEncoder.encode(query, UTF8);
    requestUrl = request;

    HttpClient client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpGet get = new HttpGet(request);
    get.setHeader("Accept", "application/rdf+xml");

    StringBuilder result = new StringBuilder();
    try {
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            String msg = "Bad result from SPARQL endpoint: " + status;
            System.err.println(msg);
            throw new HttpClientException(msg);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStreamReader resultStream = new InputStreamReader(entity.getContent());
            char[] buffer = new char[BUFFER_SIZE];
            int len;
            while ((len = resultStream.read(buffer)) >= 0)
                result.append(buffer, 0, len);
            resultStream.close();
        } else {
            String msg = "No data in response from SPARQL endpoint";
            System.out.println(msg);
            throw new HttpClientException(msg);
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("Unsupported encoding returned from SPARQL endpoint: " + e.getMessage());
        throw e;
    } catch (IOException ioe) {
        System.err.println("Error communicating with SPARQL endpoint: " + ioe.getMessage());
        throw ioe;
    }
    return result.toString();
}

From source file:org.seasr.meandre.components.nlp.calais.OpenCalaisClient.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    String text = DataTypeParser.parseAsString(cc.getDataComponentFromInput(IN_TEXT))[0];

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.useragent", "SEASR " + getClass().getSimpleName());
    try {// www .ja va  2s .c o m
        HttpPost post = new HttpPost(CALAIS_URL);
        post.setEntity(new StringEntity(text, _charset));
        for (Entry<String, String> entry : _headers.entrySet())
            post.setHeader(entry.getKey(), entry.getValue());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpClient.execute(post, responseHandler);

        cc.pushDataComponentToOutput(OUT_RESPONSE, BasicDataTypesTools.stringToStrings(response));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.softcatala.corrector.LanguageToolRequest.java

public Suggestion[] Request(String text) {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
    // Limit// www . j  av a 2s  . co  m
    HttpURLConnection uc = null;

    try {

        String url = BuildURL();

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        FillPostFields(httpPost, text);
        Log.d(TAG, "Request start:" + url);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        InputStream inputStream = httpResponse.getEntity().getContent();

        String result = toString(inputStream);
        Configuration.getInstance().incConnections();
        Configuration.getInstance().setLastConnection(new Date());
        Log.d(TAG, "Request result: " + result);
        return languageToolParsing.GetSuggestions(result);
    } catch (Exception e) {
        Log.e(TAG, "Error reading stream from URL.", e);
    }
    Suggestion[] suggestions = {};
    return suggestions;
}

From source file:org.centum.android.communicators.StudyStackCommunicator.java

private String getJSONData(URI uri) throws IOException {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
    HttpGet request = new HttpGet();
    request.setHeader("Content-Type", "text/plain; charset=utf-8");
    request.setURI(uri);/*ww w  . j a v a 2  s  .  c  om*/
    HttpResponse response = client.execute(request);
    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer stringBuffer = new StringBuffer("");
    String line;

    String NL = System.getProperty("line.separator");

    while ((line = in.readLine()) != null) {
        stringBuffer.append(line + NL);
    }
    in.close();

    return stringBuffer.toString();
}

From source file:org.wso2.dss.integration.test.jira.issues.DS937BoxcarringTestCase.java

public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.socket.timeout", 120000);
    HttpPost httpPost = new HttpPost(endpoint);

    if (sessionID == null) {
        sessionID = "11";
    }/*from  w w w  .java2s . c om*/
    headers.put("Cookie", sessionID);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }
    if (content != null) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Header[] responseHeaders = httpResponse.getHeaders("Set-Cookie");
    if (responseHeaders != null && responseHeaders.length > 0) {
        sessionID = responseHeaders[0].getValue();
    }
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}

From source file:com.basho.riak.client.http.util.ClientUtils.java

/**
 * Construct a new {@link HttpClient} instance given a {@link RiakConfig}.
 * /*from   www .j av a2s.  c o  m*/
 * @param config
 *            {@link RiakConfig} containing HttpClient configuration
 *            specifics.
 * @return A new {@link HttpClient}
 */
public static HttpClient newHttpClient(RiakConfig config) {

    HttpClient http = config.getHttpClient();
    ClientConnectionManager m;

    if (http == null) {
        m = new PoolingClientConnectionManager();
        if (config.getMaxConnections() != null) {
            ((PoolingClientConnectionManager) m).setMaxTotal(config.getMaxConnections());
            ((PoolingClientConnectionManager) m).setDefaultMaxPerRoute(config.getMaxConnections());
        }
        http = new DefaultHttpClient(m);

        if (config.getRetryHandler() != null) {
            ((DefaultHttpClient) http).setHttpRequestRetryHandler(config.getRetryHandler());
        }
    }

    HttpParams cp = http.getParams();
    if (config.getTimeout() != null) {
        cp.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, config.getTimeout());
        cp.setIntParameter(AllClientPNames.SO_TIMEOUT, config.getTimeout());
    }

    return http;
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnectorTest.java

@Test
public void testProxyAuth() {
    final String host = "host";
    final int port = 1234;

    when(proxySettings.isEnabled()).thenReturn(true);
    when(proxySettings.getHostname()).thenReturn(host);
    when(proxySettings.getPort()).thenReturn(port);

    when(proxySettings.getProxyAuthentication()).thenReturn(proxyAuth);
    when(proxyAuth.getUsername()).thenReturn("user");
    when(proxyAuth.getPassword()).thenReturn("pass");

    final HttpClient client = underTest.client();
    final HttpParams params = client.getParams();

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), notNullValue());

    assertThat(((DefaultHttpClient) client).getCredentialsProvider().getCredentials(new AuthScope(host, port)),
            notNullValue());/*from  w ww.j  a  v  a 2 s .c o m*/
}

From source file:cl.mmoscoso.geocomm.sync.GeoCommGetPointsAsyncTask.java

@Override
protected Boolean doInBackground(Void... params) {

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams httpParams = httpclient.getParams();
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

    HttpPost httppost = new HttpPost(this.hostname);

    //http://172.16.50.35/~ramirez/testAddPoint.php
    //http://172.16.57.132/~laost/Symfony/web/app_dev.php/addPoint/

    try {/*from   w  ww.j  ava2  s  . c  om*/
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(this.id)));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int responseCode = response.getStatusLine().getStatusCode();
        switch (responseCode) {
        case 200:
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity);
                //Log.i(TAGNAME, responseBody);
                JSONObject jObj, point;
                try {
                    //Log.i(TAGNAME, "tamao: "+ responseBody);
                    jObj = new JSONObject(responseBody);
                    //point = new JSONObject(jObj.getString("point1"));
                    //Log.i(TAGNAME, "tamao22: "+ jObj.length());
                    //Log.i(TAGNAME, "VER: "+ point.names());
                    //Log.i(TAGNAME, "tamao: "+ jObj.names().getString(0));
                    for (int i = 0; i < jObj.length(); i++) {
                        point = new JSONObject(jObj.getString(jObj.names().getString(i)));
                        //Log.i(TAGNAME, "VER2: "+ jObj.getString(jObj.names().getString(i)));
                        points.add(new GeoCommPoint(point.getInt("id"), point.getDouble("longitude"),
                                point.getDouble("latitude"), point.getString("name"),
                                point.getString("description")));
                        //Log.i(TAGNAME, points.get(i).getName());
                        //Log.i(TAGNAME, "lat: "+points.get(i).getLatitude());
                        //Log.i(TAGNAME, "long: "+points.get(i).getLongitude());
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            break;
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return true;
}

From source file:cl.mmoscoso.geocomm.sync.GeoCommCreatePointAsyncTask.java

@Override
protected Boolean doInBackground(Void... params) {

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams httpParams = httpclient.getParams();
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

    HttpPost httppost = new HttpPost(this.hostname);

    //http://172.16.50.35/~ramirez/testAddPoint.php
    //http://172.16.57.132/~laost/Symfony/web/app_dev.php/addPoint/

    try {//  w w w .j  a v a2s . c  om
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("name", this.name));
        nameValuePairs.add(new BasicNameValuePair("description", this.desc));
        nameValuePairs.add(new BasicNameValuePair("latitude", this.latitude));
        nameValuePairs.add(new BasicNameValuePair("longitude", this.longitude));
        nameValuePairs.add(new BasicNameValuePair("route", Integer.toString(this.id_route)));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int responseCode = response.getStatusLine().getStatusCode();
        Log.i(TAGNAME, "ERROR: " + responseCode);
        switch (responseCode) {
        default:
            Log.i(TAGNAME, "ERROR");
            //Toast.makeText(this.context,R.string.error_not200code, Toast.LENGTH_SHORT).show();
            break;
        case 200:
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity);
                //Log.i(TAGNAME, responseBody);
                JSONObject jObj, point;
                try {
                    Log.i(TAGNAME, "tamao: " + responseBody);
                    jObj = new JSONObject(responseBody);
                    this.status = jObj.getInt("status");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            break;
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return true;
}