Example usage for org.apache.http.impl.client DefaultHttpClient execute

List of usage examples for org.apache.http.impl.client DefaultHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient execute.

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request, final HttpContext context)
        throws IOException, ClientProtocolException 

Source Link

Usage

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse basicAuthRequest(String url, String username, String password,
        DefaultHttpClient client) throws HttpUtilsException {
    HttpGet get = new HttpGet(url);

    client.getCredentialsProvider().setCredentials(new AuthScope(null, 443),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);
    HttpResponse response;//from  ww  w.  j  a v a  2 s.co  m
    try {
        response = client.execute(get, localcontext);
    } catch (ClientProtocolException e) {
        throw new HttpUtilsException("Invalid http protocol", e);
    } catch (IOException e) {
        throw new HttpUtilsException(e.getMessage(), e);
    }
    return response;
}

From source file:com.fabula.android.timeline.sync.ServerDownloader.java

/**
 * Method that fetches JSON-data from a URL
 * /*w  ww  . j av a  2  s.c  o m*/
 * @param url Address to service that provide JSON
 * @return data as {@link InputStream}
 */
public static InputStream getJSONData(String url) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "TimelineAndroid");
    InputStream data = null;
    try {
        HttpHost targetHost = new HttpHost(Constants.GOOGLE_APP_ENGINE_URL, 80, "http");
        HttpGet httpGet = new HttpGet(url);
        // Make sure the server knows what kind of a response we will accept
        httpGet.addHeader("Accept", "application/json");
        // Also be sure to tell the server what kind of content we are sending
        httpGet.addHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(targetHost, httpGet);
        data = null;
        try {
            data = response.getEntity().getContent();
        } catch (NullPointerException e) {
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return data;
}

From source file:com.bjorsond.android.timeline.sync.ServerDownloader.java

/**
 * Method that fetches JSON-data from a URL
 * /* w w w  .  j a  v a 2s . com*/
 * @param url Address to service that provide JSON
 * @return data as {@link InputStream}
 */
public static InputStream getJSONData(String url) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "TimelineAndroid");
    InputStream data = null;
    try {
        HttpHost targetHost = new HttpHost(Constants.GOOGLE_APP_ENGINE_URL, 80, "http");
        HttpGet httpGet = new HttpGet(url);
        // Make sure the server knows what kind of a response we will accept
        httpGet.addHeader("Accept", "application/json");
        // Also be sure to tell the server what kind of content we are sending
        httpGet.addHeader("Content-Type", "application/json");

        HttpResponse response = httpClient.execute(targetHost, httpGet);
        data = null;
        try {
            data = response.getEntity().getContent();
        } catch (NullPointerException e) {
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return data;
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request, HttpContext context,
        String message, Class<T> clz, boolean isReturnServerError) throws XtentisException {
    if (null == request) {
        throw new IllegalArgumentException("null request"); //$NON-NLS-1$
    }/*from  w  w w. j a  v a 2 s . com*/
    HttpResponse response = null;
    try {
        response = client.execute(request, context);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null && statusLine.getStatusCode() == 501) {
            throw new OperationIgnoredException(Messages.HttpClientUtil_Error_501);
        }

        return wrapResponse(response, message, clz, isReturnServerError);
    } catch (OperationIgnoredException ex) {
        throw ex;
    } catch (InternalServerErrorException ex) {
        throw ex;
    } catch (XtentisException ex) {
        throw ex;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        request.abort();
        throw new XtentisException(e.getMessage(), e);
    } finally {
        closeResponse(response);
    }
}

From source file:de.fuberlin.agcsw.heraclitus.svont.client.core.ChangeLog.java

public static void updateChangeLog(OntologyStore os, SVoNtProject sp, String user, String pwd) {

    //load the change log from server

    try {/*www . j  av a  2  s.co m*/

        //1. fetch Changelog URI

        URI u = sp.getChangelogURI();

        //2. search for change log owl files
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(u.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(user, pwd));

        HttpGet httpget = new HttpGet(u);

        System.out.println("executing request" + httpget.getRequestLine());

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(httpget, responseHandler);
        System.out.println(response);
        List<String> files = ChangeLog.extractChangeLogFiles(response);

        ArrayList<ChangeLogElement> changelog = sp.getChangelog();
        changelog.clear();

        //4. sort the revisions

        for (int i = 0; i < files.size(); i++) {
            String fileName = files.get(i);
            System.out.println("rev sort: " + fileName);
            int rev = Integer.parseInt(fileName.split("\\.")[0]);
            changelog.add(new ChangeLogElement(URI.create(u + fileName), rev));
        }

        Collections.sort(changelog, new SortChangeLogsElementsByRev());

        //show sorted changelog

        System.out.print("[");
        for (ChangeLogElement cle : changelog) {
            System.out.print(cle.getRev() + ",");
        }
        System.out.println("]");

        //5. map revision with SVN revisionInformations
        mapRevisionInformation(os, sp, changelog);

        //6. load change log files
        System.out.println("Load Changelog Files");
        for (String s : files) {
            System.out.println(s);
            String req = u + s;
            httpget = new HttpGet(req);
            response = client.execute(httpget, responseHandler);
            //            System.out.println(response);

            // save the changelog File persistent
            IFolder chlFold = sp.getChangeLogFolder();
            IFile chlFile = chlFold.getFile(s);
            if (!chlFile.exists()) {
                chlFile.create(new ByteArrayInputStream(response.getBytes()), true, null);
            }

            os.getOntologyManager().loadOntology(new ReaderInputSource(new StringReader(response)));

        }
        System.out.println("Changelog Ontology successfully loaded");

        //Show loaded onts
        Set<OWLOntology> onts = os.getOntologyManager().getOntologies();
        for (OWLOntology o : onts) {
            System.out.println("loaded ont: " + o.getURI());
        }

        //7 refresh possibly modified Mainontology
        os.getOntologyManager().reloadOntology(os.getMainOntologyLocalURI());

        //8. recalculate Revision Information of the concept of this ontology
        sp.setRevisionMap(createConceptRevisionMap(os, sp));
        sp.saveRevisionMap();

        sp.saveRevisionInformationMap();

        //9. show MetaInfos on ConceptTree

        ConceptTree.refreshConceptTree(os, os.getMainOntologyURI());
        OntologyInformation.refreshOntologyInformation(os, os.getMainOntologyURI());

        //shutdown http connection

        client.getConnectionManager().shutdown();

    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (OWLOntologyCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OWLReasonerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SVNClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.openiot.gsn.utils.VSMonitor.java

public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception {

    String httpAddress = gsnSessionAddress.getURL();

    DefaultHttpClient client = new DefaultHttpClient();

    if (gsnSessionAddress.needsPassword()) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/),
                new UsernamePasswordCredentials(gsnSessionAddress.getUsername(),
                        gsnSessionAddress.getPassword()));
    }//  www  .  j a  va2 s  .  co m

    logger.warn("Querying server: " + httpAddress);
    HttpGet get = new HttpGet(httpAddress);

    try {
        // execute the GET, getting string directly
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = client.execute(get, responseHandler);

        parseXML(responseBody);

    } catch (HttpResponseException e) {
        errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n");
    }

    catch (UnknownHostException e) {
        errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } catch (ConnectException e) {
        errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } finally {
        // release any connection resources used by the method
        client.getConnectionManager().shutdown();
    }
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static HttpResponse postValues(HashMap<String, String> postvars, String url)
        throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    Iterator<Entry<String, String>> it = postvars.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
        Map.Entry<String, String> pairs = next;
        formparams.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
    }/*from www  .  j av  a  2s .co m*/
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpContext localContext = new BasicHttpContext();
    return httpclient.execute(httppost, localContext);
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception {

    String httpAddress = gsnSessionAddress.getURL();

    DefaultHttpClient client = new DefaultHttpClient();

    if (gsnSessionAddress.needsPassword()) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/),
                new UsernamePasswordCredentials(gsnSessionAddress.getUsername(),
                        gsnSessionAddress.getPassword()));
    }/* w  w  w  . j  a  v a  2  s  . c  o  m*/

    logger.warn("Querying server: " + httpAddress);
    HttpGet get = new HttpGet(httpAddress);

    try {
        // execute the GET, getting string directly
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = client.execute(get, responseHandler);

        parseXML(responseBody);

    } catch (HttpResponseException e) {
        errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n");
    } catch (UnknownHostException e) {
        errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n");
        nHostsDown++;
    } catch (ConnectException e) {
        errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n");
        raiseStatusTo(STATUS_CRITICAL);
        nHostsDown++;
    } finally {
        // release any connection resources used by the method
        client.getConnectionManager().shutdown();
    }
}

From source file:eu.clarin.cmdi.virtualcollectionregistry.service.impl.HttpResponseValidator.java

protected boolean checkValidityOfUri(URI uri) throws IOException {
    boolean result = false;
    DefaultHttpClient client = new DefaultHttpClient();
    HttpContext ctx = new BasicHttpContext();
    try {//w w  w  .  j  a  va  2 s . c  o  m
        HttpResponse response = client.execute(new HttpGet(uri), ctx);
        status = response.getStatusLine();
        result = status.getStatusCode() == 200;
    } finally {
        client.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.kkurahar.locationmap.HttpConnection.java

public String doGet(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    method.setHeader("Connection", "Keep-Alive");
    try {//  w  w  w . j a va2s  . c  o  m

        String resultRes = httpClient.execute(method, new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK == status) {
                    Header[] headers = response.getAllHeaders();
                    for (Header h : headers) {
                        System.out.println(h.getName() + ":" + h.getValue());
                    }
                } else {
                    throw new RuntimeException("?MG?[?");
                }
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        });
        return resultRes;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}