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) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static List<PluginRef> findPlugin(String repoUrl, String searchString, PipeOut out) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(repoUrl);

    out.print("Connecting to remote repository ... ");
    HttpResponse httpResponse = client.execute(httpGet);

    switch (httpResponse.getStatusLine().getStatusCode()) {
    case 200:/*from w ww  .  j  a v a2  s.com*/
        out.println("found!");
        break;

    case 404:
        out.println("failed! (plugin index not found: " + repoUrl + ")");
        return Collections.emptyList();

    default:
        out.println("failed! (server returned status code: " + httpResponse.getStatusLine().getStatusCode());
        return Collections.emptyList();
    }

    Pattern pattern = Pattern.compile(GeneralUtils.pathspecToRegEx("*" + searchString + "*"));

    List<PluginRef> pluginList = new ArrayList<PluginRef>();

    Yaml yaml = new Yaml();
    for (Object o : yaml.loadAll(httpResponse.getEntity().getContent())) {
        if (o == null) {
            continue;
        }

        Map map = (Map) o;
        String name = (String) map.get("name");

        if (pattern.matcher(name).matches()) {
            pluginList.add(bindToPuginRef(map));
        }
    }

    return pluginList;
}

From source file:ch.lipsch.deshortener.Deshortener.java

/**
 * Deshortens the provided uri./* w w  w.j  av a2 s.c o m*/
 *
 * @param uriToDeshorten
 *            The uri to deshorten.
 * @return Returns the result of the deshorten process. The result is only
 *         successful when the given uri returns an 30x. Then value of the
 *         Location header is returned within the result.
 * @throws IllegalArgumentException
 *             If the provided uri is invalid.
 */
public static Result deshorten(Uri uriToDeshorten) {
    // Checks if the url shortener shows a preview
    if (checkForPreview(uriToDeshorten)) {
        return new Result(ResultType.SHOWS_PREVIEW);
    }

    // Open the network connetion
    HttpGet get = new HttpGet(uriToDeshorten.toString());
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams clientParams = client.getParams();
    HttpClientParams.setRedirecting(clientParams, false);
    HttpResponse response = null;
    try {
        response = client.execute(get);
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Unable to communicate to shortened url: " + uriToDeshorten.toString(), e);
        return new Result(ResultType.NETWORK_ERROR);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Unable to communicate to shortened url: " + uriToDeshorten.toString(), e);
        return new Result(ResultType.NETWORK_ERROR);
    }

    // Check for redirection
    boolean isRedirection = ((response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY)
            || (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
            || (response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER));
    if (response != null && isRedirection) {
        Header header = response.getFirstHeader("Location");
        String redirectValue = header.getValue();
        Uri deshortenedUri = Uri.parse(redirectValue);
        return new Result(deshortenedUri);
    } else {
        return new Result(ResultType.CANNOT_DESHORTEN);
    }
}

From source file:com.wiyun.engine.network.Network.java

static HttpResponse syncExec(DefaultHttpClient client, HttpUriRequest request) {
    try {/*  ww  w.j  a va2  s . com*/
        HttpResponse response = client.execute(request);
        return response;
    } catch (Exception e) {
        return null;
    }
}

From source file:jsonclient.JsonClient.java

private static String postToURL(String url, String message, DefaultHttpClient httpClient)
        throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
    HttpPost postRequest = new HttpPost(url);

    StringEntity input = new StringEntity(message);
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from w w w  .j  av a 2s  .c  om*/

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;
    StringBuffer totalOutput = new StringBuffer();
    //System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        //System.out.println(output);
        totalOutput.append(output);
    }
    return totalOutput.toString();
}

From source file:com.fpmislata.clientejson.ClienteProductoTest.java

private static List<Producto> getListProducto(String url) throws IOException {
    // Crea el cliente para realizar la conexion
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Crea el mtodo con el que va a realizar la operacion
    HttpGet httpGet = new HttpGet(url);
    // Aade las cabeceras al metodo
    httpGet.addHeader("accept", "application/json; charset=UTF-8");
    httpGet.addHeader("Content-type", "application/json; charset=UTF-8");
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpGet);
    // Obtenemos un objeto String como respuesta del response
    String lista = readObject(response);
    // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    // Creamos el tipo generico que nos va a permitir devolver la lista a partir del JSON que esta en el String
    Type type = new TypeToken<List<Producto>>() {
    }.getType();//  w  ww  .  j  av  a  2 s.  c  om
    // Parseamos el String lista a un objeto con el gson, devolviendo as un objeto List<Categoria>
    return gson.fromJson(lista, type);
}

From source file:sg.macbuntu.android.pushcontacts.DeviceRegistrar.java

private static HttpResponse makeRequestNoRetry(Context context, String deviceRegistrationID, String url,
        boolean newToken) throws Exception {
    // Get chosen user account
    SharedPreferences settings = Prefs.get(context);
    String accountName = settings.getString("accountName", null);
    if (accountName == null)
        throw new Exception("No account");

    // Get auth token for account
    Account account = new Account(accountName, "com.google");
    String authToken = getAuthToken(context, account);
    if (authToken == null) {
        throw new PendingAuthException(accountName);
    }/*ww  w. j ava2  s  .c o  m*/
    if (newToken) {
        // Invalidate the cached token
        AccountManager accountManager = AccountManager.get(context);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(context, account);
    }

    // Register device with server
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = url + "?devregid=" + deviceRegistrationID;
    URI uri = new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    HttpResponse res = client.execute(method);
    return res;
}

From source file:com.ilearnrw.reader.utils.HttpHelper.java

public static HttpResponse get(String url) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = null;//w  w w.j av a  2  s. co  m

    HttpConnectionParams.setSoTimeout(client.getParams(), 25000);

    HttpGet get = new HttpGet(url);
    get.setHeader("Authorization", "Basic " + authString);
    try {
        response = client.execute(get);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return response;
}

From source file:net.sf.asap.Player.java

private static InputStream httpGet(Uri uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(uri.toString());
    HttpResponse response = client.execute(request);
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() != 200)
        throw new IOException("HTTP error " + status);
    return response.getEntity().getContent();
}

From source file:org.jboss.capedwarf.tools.BulkLoader.java

private static void doDump(Arguments args) {
    String url = getUrl(args);/*  w  w  w  .  j a  va 2  s .  c om*/
    String filename = getFilename(args);
    int packetSize = getPacketSize(args);

    File file = new File(filename);
    if (file.exists()) {
        System.out.println("WARNING: File " + filename + " already exists!");
        System.exit(1);
    }

    System.out.println("Dumping data from " + url + " to " + filename + " in packets of size " + packetSize);

    DumpFileFacade dumpFileFacade = new DumpFileFacade(file);
    try {
        DefaultHttpClient client = new DefaultHttpClient(new SingleClientConnManager());
        try {
            HttpGet get = new HttpGet(url);
            get.getParams().setParameter("action", "dump");
            System.out.println("Downloading packet of " + packetSize + " entities");
            HttpResponse response = client.execute(get);
            DataInputStream in = new DataInputStream(response.getEntity().getContent());
            while (true) {
                byte[] idBytes = readArray(in);
                if (idBytes == null) {
                    break;
                }
                byte[] entityPbBytes = readArray(in);
                byte[] sortKeyBytes = readArray(in);

                dumpFileFacade.add(idBytes, entityPbBytes, sortKeyBytes);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        dumpFileFacade.close();
    }

}

From source file:org.broadinstitute.gatk.utils.help.ForumAPIUtils.java

private static String httpPost(String data, String URL) {
    try {/*from   www .j  a v a 2 s. com*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(URL);

        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output = "";
        String line;
        System.out.println("Output from Server .... \n");
        while ((line = br.readLine()) != null) {
            output += (line + '\n');
            System.out.println(line);
        }

        br.close();
        httpClient.getConnectionManager().shutdown();
        return output;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return null;
}