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:uk.codingbadgers.bUpload.ImageUploadThread.java

/**
 * Upload the buffered image to imgur//  w w  w  .jav  a  2s.  c  om
 * 
 * @param image The image to upload
 * @return a formatted url to the uploaded image, or an error message
 */
private boolean upload(Screenshot image) {
    try {
        String title = bUpload.DATE_FORMAT.format(new Date());
        String description = "A minecraft screenshot ";

        if (Minecraft.getMinecraft().isSingleplayer()) {
            description += "in " + Minecraft.getMinecraft().getIntegratedServer().getFolderName();
        } else {
            description += "on " + bUpload.server + (bUpload.port != 25565 ? ":" + bUpload.port : "");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image.image, "png", baos);
        String data = Base64.encodeBase64String(baos.toByteArray());

        List<NameValuePair> arguments = new ArrayList<NameValuePair>(3);
        arguments.add(new BasicNameValuePair("client_id", ImgurProfile.CLIENT_ID));
        arguments.add(new BasicNameValuePair("image", data));
        arguments.add(new BasicNameValuePair("type", "base64"));
        arguments.add(new BasicNameValuePair("title", title));
        arguments.add(new BasicNameValuePair("description", description));

        HttpPost hpost = new HttpPost("https://api.imgur.com/3/upload");
        hpost.setEntity(new UrlEncodedFormEntity(arguments));

        if (ImgurProfile.getAccessToken() != null) {
            hpost.addHeader("Authorization", "Bearer " + ImgurProfile.getAccessToken());
        } else {
            hpost.addHeader("Authorization", "Client-ID " + ImgurProfile.CLIENT_ID);
        }

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse resp = client.execute(hpost);
        String result = EntityUtils.toString(resp.getEntity());

        JsonObject responce = new JsonParser().parse(result).getAsJsonObject();
        JsonObject responceData = responce.get("data").getAsJsonObject();

        if (responce.has("success") && responce.get("success").getAsBoolean()) {
            final String uploadUrl = responceData.get("link").getAsString();

            bUpload.addUploadedImage(new UploadedImage(title, uploadUrl, image, false));
            bUpload.sendChatMessage("image.upload.success", true, uploadUrl);

            if (bUpload.SHOULD_COPY_TO_CLIPBOARD) {
                GuiScreen.setClipboardString(uploadUrl);
                bUpload.sendChatMessage("image.upload.copy", true);
            }
        } else {
            bUpload.sendChatMessage("image.upload.fail", true);
            bUpload.sendChatMessage(responceData.get("error").getAsString(), false);
            return false;
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        bUpload.sendChatMessage("image.upload.fail", true);
        return false;
    }
}

From source file:com.procleus.brime.utils.JSONParser.java

public JSONObject getJSONFromUrl(String url) {

    try {//  w  w  w  . j  a v  a 2s .  c o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
}

From source file:com.cybrosys.currency.Currency_JSONParsor.java

public JSONObject getJSONformUrl(String url) {
    try {/*from  w w w . ja  v a2s  . c om*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (IOException e) {

        e.printStackTrace();
    }
    try {
        jobj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jobj;
}

From source file:lt.appcamp.appcamp16.utils.DrawableManager.java

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    InputStream cached = CacheManager.read(urlString);

    if (cached != null)
        return cached;

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);

    InputStream stream = response.getEntity().getContent();

    InputStreamCopier copier = new InputStreamCopier(stream);

    CacheManager.write(urlString, copier.getCopy());

    return copier.getCopy();
}

From source file:WSpatern.FileReview.java

public void getFileToPreview(String token, String id) {

    try {/*from  ww w .  j ava2 s  .  c  om*/
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("https://documenta-dms.com/DMSWS/api/v1/file/" + token + "/pdf_by_id/" + id);
        HttpResponse response = client.execute(get);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            line = line + line;
            System.out.println(line);

            //parseXML(line);

        }

        getDate(line);
    } catch (IOException ex) {
        Logger.getLogger(ValidTokenWS.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.apache.tika.parser.captioning.tf.TensorflowRESTCaptioner.java

@Override
public void initialize(Map<String, Param> params) throws TikaConfigException {
    try {//from ww w .  ja v a2s  .  com
        healthUri = URI.create(apiBaseUri + "/ping");
        apiUri = URI.create(apiBaseUri + String.format(Locale.getDefault(),
                "/caption/image?beam_size=%1$d&max_caption_length=%2$d", captions, maxCaptionLength));

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(new HttpGet(healthUri));
        available = response.getStatusLine().getStatusCode() == 200;

        LOG.info("Available = {}, API Status = {}", available, response.getStatusLine());
        LOG.info("Captions = {}, MaxCaptionLength = {}", captions, maxCaptionLength);
    } catch (Exception e) {
        available = false;
        throw new TikaConfigException(e.getMessage(), e);
    }
}

From source file:org.jboss.as.test.clustering.single.web.SimpleWebTestCase.java

@Test
@OperateOnDeployment("deployment-single")
public void test(@ArquillianResource(SimpleServlet.class) URL baseURL)
        throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();

    String url = baseURL.toString() + "simple";

    try {/* w  w w.  ja v a 2s  . c om*/
        HttpResponse response = client.execute(new HttpGet(url));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet(url));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        // This won't be true unless we have somewhere to which to replicate or session persistence is configured (current default)
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.github.egonw.rrdf.RJenaHelper.java

public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password)
        throws Exception {
    StringMatrix table = null;/*  www.  j av a  2  s .c o m*/

    // use Apache for doing the SPARQL query
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Set credentials on the client
    if (user != null) {
        URL endpointURL = new URL(endpoint);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(user, password));
        httpclient.setCredentialsProvider(credsProvider);
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("query", queryString));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(endpoint);
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200)
        throw new HttpException(
                "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity responseEntity = response.getEntity();
    InputStream in = responseEntity.getContent();

    // now the Jena part
    ResultSet results = ResultSetFactory.fromXML(in);
    // also use Jena for getting the prefixes...
    Query query = QueryFactory.create(queryString);
    PrefixMapping prefixMap = query.getPrefixMapping();
    table = convertIntoTable(prefixMap, results);

    in.close();
    return table;
}

From source file:com.arthackday.killerapp.GCMIntentService.java

@Override
protected void onRegistered(Context ctxt, String regId) {
    Log.i(getClass().getSimpleName(), "onRegistered: " + regId);

    URL url;//from ww  w . ja va  2s.  com
    try {
        url = new URL(String.format(GCM_URL, this.getPackageName(), regId));

        // --This code works for updating a record from the feed--
        HttpPut httpPut = new HttpPut(url.toString());

        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(httpPut);
        HttpEntity entity1 = response.getEntity();

        if (entity1 != null && (response.getStatusLine().getStatusCode() == 201
                || response.getStatusLine().getStatusCode() == 200)) {
            // --just so that you can view the response, this is optional--
            int sc = response.getStatusLine().getStatusCode();
            String sl = response.getStatusLine().getReasonPhrase();
        } else {
            int sc = response.getStatusLine().getStatusCode();
            String sl = response.getStatusLine().getReasonPhrase();
        }

    } catch (MalformedURLException e) {
        Log.wtf("ArtHackDay", "failure");
    } catch (ClientProtocolException e) {
        Log.wtf("ArtHackDay", "failure");
    } catch (IOException e) {
        Log.wtf("ArtHackDay", "failure");
    }
}

From source file:com.streaming.sweetplayer.utils.JSONParser.java

public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {/*w ww.  j a v  a 2 s .  co  m*/
        // DefaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
}