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:org.opens.tanaguru.contentloader.DownloaderImpl.java

private String download(String url) {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet(url);

    httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(10000));
    httpclient.getParams().setParameter("http.connection.timeout", Integer.valueOf(10000));

    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = null;/*from  www .ja v  a 2  s .c  o  m*/
    try {
        responseBody = httpclient.execute(httpget, responseHandler);
    } catch (HttpResponseException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (UnknownHostException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (SSLPeerUnverifiedException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    } catch (IOException ex) {
        LOGGER.warn(ex.getMessage() + " " + url);
        return "";
    }
    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
    return responseBody;
}

From source file:de.telekom.cldii.util.rssparser.RSSReader.java

/**
 * Instantiate a thread-safe HTTP client to retrieve RSS feeds. The injected
 * {@link HttpClient} implementation must be thread-safe.
 * /*from w  ww  .  j a  va 2  s  .com*/
 * @param httpclient thread-safe HTTP client implementation
 * @param parser thread-safe RSS parser SPI implementation
 */
public RSSReader(HttpClient httpclient, RSSParserSPI parser) {
    this.httpclient = httpclient;
    HttpParams httpParams = httpclient.getParams();
    HttpConnectionParams.setSoTimeout(httpParams, ApplicationConstants.RSS_TIMEOUT);

    this.parser = parser;
}

From source file:org.dspace.submit.lookup.ArXivService.java

protected List<Record> search(String query, String arxivid, int max_result) throws IOException, HttpException {
    List<Record> results = new ArrayList<Record>();
    HttpGet method = null;// ww  w. j  a  va2s .  co m
    try {
        HttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

        try {
            URIBuilder uriBuilder = new URIBuilder("http://export.arxiv.org/api/query");
            uriBuilder.addParameter("id_list", arxivid);
            uriBuilder.addParameter("search_query", query);
            uriBuilder.addParameter("max_results", String.valueOf(max_result));
            method = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException ex) {
            throw new HttpException(ex.getMessage());
        }

        // Execute the method.
        HttpResponse response = client.execute(method);
        StatusLine responseStatus = response.getStatusLine();
        int statusCode = responseStatus.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("arXiv query is not valid");
            else
                throw new RuntimeException("Http call failed: " + responseStatus);
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder db = factory.newDocumentBuilder();
            Document inDoc = db.parse(response.getEntity().getContent());

            Element xmlRoot = inDoc.getDocumentElement();
            List<Element> dataRoots = XMLUtils.getElementList(xmlRoot, "entry");

            for (Element dataRoot : dataRoots) {
                Record crossitem = ArxivUtils.convertArxixDomToRecord(dataRoot);
                if (crossitem != null) {
                    results.add(crossitem);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("ArXiv identifier is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return results;
}

From source file:com.oakclub.android.base.OakClubApplication.java

private void pingActivities() {
    Thread SplashTimer = new Thread() {
        public void run() {
            try {
                while (true) {
                    HttpClient hClient = new DefaultHttpClient();
                    HttpConnectionParams.setConnectionTimeout(hClient.getParams(), 20000);
                    HttpConnectionParams.setSoTimeout(hClient.getParams(), 60000);
                    try {
                        HttpGet hget = new HttpGet();
                        String headerValue = "UsernameToken " + "Username=\""
                                + OakClubBaseActivity.facebook_user_id + "\", AccessToken=\""
                                + OakClubBaseActivity.access_token
                                + "\", Nonce=\"1ifn7s\", Created=\"2013-10-19T07:12:43.407Z\"";
                        hget.setHeader(Constants.HEADER_X_WSSE, headerValue);
                        hget.setHeader(Constants.HEADER_ACCEPT, "application/json");
                        hget.setHeader(Constants.HEADER_ACCEPT, "text/html");
                        hget.setHeader(Constants.HTTP_USER_AGENT, "Android");
                        hget.setURI(new URI(getApplicationContext().getString(R.string.default_server_address)
                                + "/pingActivities"));
                        HttpResponse response = hClient.execute(hget);
                        StatusLine statusLine = response.getStatusLine();

                        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            response.getEntity().writeTo(out);
                            out.close();
                        }// w  w w . j ava 2  s.  c om
                    } catch (ConnectTimeoutException e) {
                    } catch (Exception e) {
                    }
                    sleep(60000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    SplashTimer.start();
}

From source file:org.wso2.dss.integration.test.sparql.SPARQLServiceTestCase.java

public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }/*from  w  w w. j a va2s .c o m*/
    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);
    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:cl.mmoscoso.geocomm.sync.GeoCommRegisterAsyncTask.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);

    try {/*from   ww  w.  j  a  v a 2 s  .  c o m*/
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("username", this.name));
        nameValuePairs.add(new BasicNameValuePair("password", this.pass));
        nameValuePairs.add(new BasicNameValuePair("email", this.e_mail));
        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;
                try {
                    //Log.i(TAGNAME, "tamao: "+ responseBody);
                    jObj = new JSONObject(responseBody);
                    Log.i(TAGNAME, "tamao22: " + jObj.getInt("status"));
                    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;
}

From source file:org.flakor.androidtool.net.net.HistoryTask.java

@Override
protected Integer doInBackground(String... params) {
    String branchId = params[0];/*from  ww  w  .j  a  v a  2  s.  c o m*/
    String startTime = params[1];
    String endTime = params[2];

    Debug.error("HistoryTask", "branchid:" + branchId + ";starttime:" + startTime + ";endtime:" + endTime);
    HttpPost httpPost = new HttpPost(HttpThread.SERVER_URL_REMOTE);
    List<NameValuePair> list = new ArrayList<NameValuePair>();

    list.add(new BasicNameValuePair(HttpThread.POST_FUNC, HttpThread.ACTION_HISTORY));
    list.add(new BasicNameValuePair(HttpThread.POST_BID, branchId));
    list.add(new BasicNameValuePair(HttpThread.POST_START_TIME, startTime));
    list.add(new BasicNameValuePair(HttpThread.POST_END_TIME, endTime));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        HttpClient client = new DefaultHttpClient();
        //
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
        //?
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 8000);
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, HTTP.UTF_8);

            Debug.error("HistoryTask", result);
            application = (MyApplication) context.getApplicationContext();
            int resultCode = JsonParser.parseHistory(result, application);

            return resultCode;
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return -1;
}

From source file:org.dspace.submit.lookup.CrossRefService.java

public List<Record> search(Context context, String title, String authors, int year, int count, String apiKey)
        throws IOException, HttpException {
    HttpGet method = null;/* w  w  w .  jav a2 s.  c  o m*/
    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

        URIBuilder uriBuilder = new URIBuilder("http://search.labs.crossref.org/dois");

        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(title)) {
            sb.append(title);
        }
        sb.append(" ");
        if (StringUtils.isNotBlank(authors)) {
            sb.append(authors);
        }
        String q = sb.toString().trim();
        uriBuilder.addParameter("q", q);

        uriBuilder.addParameter("year", year != -1 ? String.valueOf(year) : "");
        uriBuilder.addParameter("rows", count != -1 ? String.valueOf(count) : "");
        method = new HttpGet(uriBuilder.build());

        // Execute the method.
        HttpResponse response = client.execute(method);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Http call failed:: " + statusLine);
        }

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Map>>() {
        }.getType();
        List<Map> json = gson.fromJson(
                IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8), listType);
        Set<String> dois = new HashSet<String>();
        for (Map r : json) {
            dois.add(SubmissionLookupUtils.normalizeDOI((String) r.get("doi")));
        }
        method.releaseConnection();

        return search(context, dois, apiKey);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:android.net.http.HttpsThroughHttpProxyTest.java

public void testConnectViaHttpProxyToHttps() throws IOException, InterruptedException {
    TestSSLContext testSSLContext = TestSSLContext.create();

    MockWebServer proxy = new MockWebServer();
    proxy.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
    MockResponse connectResponse = new MockResponse().setResponseCode(200);
    connectResponse.getHeaders().clear();
    proxy.enqueue(connectResponse);/*from   w ww  .  j av a  2s .  c  om*/
    proxy.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via a secure proxy"));
    proxy.play();

    HttpClient httpProxyClient = new DefaultHttpClient();
    HttpHost proxyHost = new HttpHost("localhost", proxy.getPort());
    httpProxyClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    httpProxyClient.getConnectionManager().getSchemeRegistry()
            .register(new Scheme("https", sslSocketFactory, 443));

    HttpResponse response = httpProxyClient.execute(new HttpGet("https://android.com/foo"));
    assertEquals("this response comes via a secure proxy", contentToString(response));

    RecordedRequest connect = proxy.takeRequest();
    assertEquals("Connect line failure on proxy " + proxyHost.toHostString(),
            "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine());
    assertContains(connect.getHeaders(), "Host: android.com");

    RecordedRequest get = proxy.takeRequest();
    assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
    assertContains(get.getHeaders(), "Host: android.com");
}

From source file:cl.mmoscoso.geocomm.sync.GeoCommDeletePointAsyncTask.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 {/*  ww  w  .j  ava2 s .co  m*/
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(this.id_point)));
        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;
                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;
}