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

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

Introduction

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

Prototype

public DefaultHttpClient() 

Source Link

Usage

From source file:com.deployd.Deployd.java

public static JSONObject delete(String uri) throws ClientProtocolException, IOException, JSONException {

    HttpDelete post = new HttpDelete(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}

From source file:tern.repository.TernRepositoryHelper.java

/**
 * Load tern modules coming from the given repository.json URL.
 * //w  w  w.  ja  v  a  2 s  .  c  o  m
 * @param repositoryURL
 *            repository URL.
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws TernException
 */
public static List<ITernModule> loadModules(String repositoryURL) throws IOException, TernException {
    // load repository.json with HTTP client.
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(repositoryURL);
    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity entity = httpResponse.getEntity();
    InputStream in = entity.getContent();
    // Check the status
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        String message = IOUtils.toString(in);
        if (StringUtils.isEmpty(message)) {
            throw new TernException(statusLine.toString());
        }
        throw new TernException(message);
    }

    // read JSON and create tern modules list
    JsonObject repository = JsonObject.readFrom(new InputStreamReader(in));
    ITernModule module = null;
    List<ITernModule> modules = new ArrayList<ITernModule>();
    for (Member member : repository) {
        module = new TernModuleToDownload(member.getName(), (JsonObject) member.getValue());
        modules.add(module);
    }
    return modules;
}

From source file:org.artags.android.app.util.http.HttpUtil.java

/**
 * Post data and attachements//from   ww w .j a v a2s  .  co  m
 * @param url The POST url
 * @param params Parameters
 * @param files Files
 * @return The return value
 * @throws HttpException If an error occurs
 */
public static String post(String url, HashMap<String, String> params, HashMap<String, File> files)
        throws HttpException {
    String ret = "";
    try {
        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(url);

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String key : files.keySet()) {
            FileBody bin = new FileBody(files.get(key));
            reqEntity.addPart(key, bin);
        }

        for (String key : params.keySet()) {
            String val = params.get(key);

            reqEntity.addPart(key, new StringBody(val, Charset.forName("UTF-8")));
        }
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);

        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            Log.i("ARTags:HttpUtil:Post:Response", ret);
        }

        //return response;
    } catch (Exception e) {
        Log.e("ARTags:HttpUtil", "Error : " + e.getMessage());
        throw new HttpException(e.getMessage());
    }
    return ret;
}

From source file:net.nordist.lloydproof.HttpJSONClient.java

public HttpJSONClient(String url) {
    super();
    httpClient = new DefaultHttpClient();
    httpRequest = new HttpPost(url);
}

From source file:eltharis.wsn.showIDActivity.java

private String executeGET(int id) throws Exception {
    HttpClient httpclient = new DefaultHttpClient(); //tutaj jest podobnie jak w showAllActivity
    HttpResponse response = httpclient/*from  ww w.  ja v  a 2  s .  c om*/
            .execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/" + Integer.toString(id)));
    StatusLine statusline = response.getStatusLine();
    Toast toast = Toast.makeText(getApplicationContext(),
            "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG);
    toast.show();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
    String responseString = out.toString();
    out.close();
    return responseString;
}

From source file:br.pub.tradutor.TradutorController.java

/**
 * Mtodo utilizado para traduo utilizando o Google Translate
 *
 * @param text Texto a ser traduzido//  ww  w .  j  a  v  a  2 s .c  om
 * @param from Idioma de origem
 * @param to Idioma de destino
 * @return Texto traduzido (no idioma destino)
 * @throws IOException
 */
public static String translate(String text, String from, String to) throws IOException {
    //Faz encode de URL, para fazer escape dos valores que vo na URL
    String encodedText = URLEncoder.encode(text, "UTF-8");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //Mtodo GET a ser executado
    HttpGet httpget = new HttpGet(String.format(TRANSLATOR, encodedText, from, to));

    //Faz a execuo
    HttpResponse response = httpclient.execute(httpget);

    //Busca a resposta da requisio e armazena em String
    String returnContent = EntityUtils.toString(response.getEntity());

    //Desconsidera tudo depois do primeiro array
    returnContent = returnContent.split("\\],\\[")[0];

    //StringBuilder que sera carregado o retorno
    StringBuilder translatedText = new StringBuilder();

    //Verifica todas as tradues encontradas, e junta todos os trechos
    Matcher m = RESULTS_PATTERN.matcher(returnContent);
    while (m.find()) {
        translatedText.append(m.group(1).trim()).append(' ');
    }

    //Retorna
    return translatedText.toString().trim();

}

From source file:com.infojobs.hereismyjob.httpmanager.HttpManager.java

public HttpManager(String str) {
    try {/*  ww w  . jav a  2s  . c  o m*/
        client = new DefaultHttpClient();
        targetHost = new HttpHost(Constants.HOST_NAME, Constants.PORT_NUMBER, Constants.HOST_SCHEME);
        // Client credentials
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("Aladdin", "open sesame"));
        // create a GET method that queries some API operation  
        request = new HttpGet(str);
        // execute the operation  
        response = client.execute(targetHost, request);

        // print the status and the contents of the response  
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(response.getEntity()));

    } catch (MalformedURLException ex) {
        Constants.showException("Malformed URL exception: " + ex);
    } catch (IOException ex) {
        Constants.showException("Input/Output exception: " + ex);
    } finally {
        // release any connection resources used by the method  
        client.getConnectionManager().shutdown();
    }
}

From source file:conexao.Conexao.java

public PlayerGames getPlayerGames(Long summonerId) {
    PlayerGames example = null;// w  ww. j a  v  a 2 s .  com
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("https://br.api.pvp.net/api/lol/br/v1.3/game/by-summoner/" + summonerId
                + "/recent?api_key=RGAPI-6b21c1fe-67a3-4222-b713-918d6609f30c");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        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 = "";
        System.out.println("Output from Server .... \n");
        /*            while ((output = br.readLine()) != null) {
        System.out.println(output);
        }*/

        do {
            output += br.readLine();
        } while (br.readLine() != null);
        // System.out.println("output: " + output);
        example = new Gson().fromJson(output, PlayerGames.class);
        httpClient.getConnectionManager().shutdown();
        // System.out.println("id: " + example.getSummonerId());
    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return example;
}

From source file:com.magi.web.WebParser.java

public String parse() throws IOException {
    System.out.println("URL: " + url);

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        int bread = 0;
        byte[] buff = new byte[512];
        StringBuffer sbuff = new StringBuffer();
        InputStream instream = entity.getContent();
        while ((bread = instream.read(buff)) != -1) {
            sbuff.append(new String(buff, 0, bread));
        }//  w  w w.  j  a v  a 2s  . com
        // Do not need the rest
        httpget.abort();

        parseText(sbuff.toString());
        return sbuff.toString();
    }

    return null;
}

From source file:br.com.grupofortress.dao.ConectaComFortressRest.java

public JSONObject atualizaVeiculos(String endereco) throws ClientProtocolException, IOException, JSONException {
    HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet(endereco);
    //request.setHeader("ApiKey", apiKey.toString());
    //request.setHeader("SecretKey", secretKey.toString());

    HttpResponse response;/* ww  w  .  j  av a 2 s . c  o  m*/
    JSONObject dadosFulltrack = null;

    response = client.execute(request);

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

    String line = "";
    String json = "";

    while ((line = rd.readLine()) != null) {
        json = json + line;
    }

    dadosFulltrack = new JSONObject(json);

    return dadosFulltrack;

}