Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

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

Prototype

HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context.

Usage

From source file:com.deployd.Deployd.java

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

    HttpGet post = new HttpGet(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:org.artags.android.app.stackwidget.util.HttpUtils.java

public static Bitmap loadBitmap(String url) {
    try {// w ww . j  a v  a  2  s . c  o  m
        final HttpClient httpClient = getHttpClient();
        final HttpResponse resp = httpClient.execute(new HttpGet(url));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);
        // Decode the bytes and return the bitmap.
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        decodeOptions.inSampleSize = 1;
        return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
    } catch (Exception e) {
        Log.w(TAG, "Problem while loading image: " + e.toString(), e);
    }
    return null;

}

From source file:com.squid.kraken.v4.auth.RequestHelper.java

public static <T> T processRequest(Class<T> type, HttpServletRequest request, HttpRequestBase req)
        throws IOException, URISyntaxException, ServerUnavailableException, ServiceException,
        SSORedirectException {//from ww w  .ja  v  a2s  .  co  m

    // set client information to the header
    String reqXFF = request.getHeader(STRING_XFF_HEADER);
    String postXFF;
    if (reqXFF != null) {
        // X-Forwarded-For header already exists in the request
        logger.info(STRING_XFF_HEADER + " : " + reqXFF);
        if (reqXFF.length() > 0) {
            // just add the remoteHost to it
            postXFF = reqXFF + ", " + request.getRemoteHost();
        } else {
            postXFF = request.getRemoteHost();
        }
    } else {
        postXFF = request.getRemoteHost();
    }

    // add a new X-Forwarded-For header containing the remoteHost
    req.addHeader(STRING_XFF_HEADER, postXFF);

    // execute the login request
    HttpResponse executeCode;
    try {
        HttpClient client = HttpClientBuilder.create().build();
        executeCode = client.execute(req);
    } catch (ConnectException e) {
        // Authentication server unavailable
        throw new ServerUnavailableException(e);
    }

    // process the result
    BufferedReader rd = new BufferedReader(new InputStreamReader(executeCode.getEntity().getContent()));

    StringBuffer resultBuffer = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        resultBuffer.append(line);
    }
    String result = resultBuffer.toString();

    T fromJson;
    Gson gson = new Gson();
    int statusCode = executeCode.getStatusLine().getStatusCode();
    if (statusCode != 200) {
        if (executeCode.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            String redirectURL = executeCode.getFirstHeader("Location").getValue();
            throw new SSORedirectException("SSO Redirect Exception", redirectURL);
        } else {
            logger.info("Error : " + req.getURI() + " resulted in : " + result);
            WebServicesException exception;
            try {
                exception = gson.fromJson(result, WebServicesException.class);
            } catch (Exception e) {
                if ((statusCode >= 500) && (statusCode < 600)) {
                    // Authentication server unavailable
                    throw new ServerUnavailableException();
                } else {
                    throw new ServiceException();
                }
            }
            throw new ServiceException(exception);
        }
    } else {
        // forward to input page displaying ok message
        try {
            fromJson = gson.fromJson(result, type);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
    return fromJson;
}

From source file:enrichment.Disambiguate.java

static ArrayList<String> getAllCreators(URI resource)
        throws URISyntaxException, ClientProtocolException, IOException {
    System.out.print("\nCreators=" + resource.toString());
    ArrayList<String> al = new ArrayList<String>();
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    String query = "CONSTRUCT {  <" + resource + "> <http://purl.org/dc/elements/1.1/creator> ?o } WHERE { <"
            + resource + "> <http://purl.org/dc/elements/1.1/creator> ?o } ";

    qparams.add(new BasicNameValuePair("query", query));
    URLEncodedUtils.format(qparams, "UTF-8");
    URI uri = URIUtils.createURI("http", "test.lobid.org", -1, "/sparql/",
            URLEncodedUtils.format(qparams, "UTF-8"), null);
    HttpGet httpget = new HttpGet(uri);
    HttpClient httpclient = new DefaultHttpClient();
    httpget.addHeader("Accept", "text/plain");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        String s;/*from   ww  w  .  j av  a 2 s.  c  om*/
        while ((s = br.readLine()) != null) {
            s = s.split(" ")[2]; // getting object
            al.add(s);
        }
    }
    return al;
}

From source file:com.codingrhemes.steamsalesmobile.JSON.java

public static String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);
    try {//from   w  w  w  .  j av  a  2 s .c  o m
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

From source file:com.liferay.mobile.android.util.PortraitUtil.java

public static String downloadPortrait(Session session, String portraitURL, OutputStream os, String modifiedDate)
        throws Exception {

    String lastModified = null;//  w  ww  . j a  v  a  2 s  . c  o m
    InputStream is = null;

    try {
        HttpGet get = new HttpGet(portraitURL);

        if (Validator.isNotNull(modifiedDate)) {
            get.addHeader(HttpUtil.IF_MODIFIED_SINCE, modifiedDate);
        }

        HttpClient client = HttpUtil.getClient(session);
        HttpResponse response = client.execute(get);

        int status = response.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            is = response.getEntity().getContent();

            int count;
            byte data[] = new byte[8192];

            while ((count = is.read(data)) != -1) {
                os.write(data, 0, count);
            }

            Header header = response.getLastHeader(HttpUtil.LAST_MODIFIED);
            lastModified = header.getValue();
        }
    } catch (Exception e) {
        Log.e(_CLASS_NAME, "Couldn't download portrait", e);

        throw e;
    } finally {
        close(is);
        close(os);
    }

    return lastModified;
}

From source file:com.liferay.sync.engine.util.SyncClientUpdater.java

protected static HttpResponse execute(String url) {
    try {/*from  www.j  a  va2 s . co  m*/
        HttpClient httpClient = HttpClients.createDefault();

        return httpClient.execute(getHttpGet(url));
    } catch (Exception e) {
        if (_logger.isDebugEnabled()) {
            _logger.debug(e.getMessage(), e);
        }

        return null;
    }
}

From source file:org.apache.hyracks.server.test.NCServiceIT.java

private static String getHttp(String url) throws Exception {
    HttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(url);
    int statusCode;
    final HttpResponse httpResponse;
    try {
        httpResponse = client.execute(get);
        statusCode = httpResponse.getStatusLine().getStatusCode();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;//from w  ww .  j  a v  a 2 s.c  o m
    }
    String response = EntityUtils.toString(httpResponse.getEntity());
    if (statusCode == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new Exception("HTTP error " + statusCode + ":\n" + response);
    }
}

From source file:org.wso2.carbon.tfl.realtime.TflStream.java

public static void send(ArrayList<String> jsonList, String endPoint) {
    for (String data : jsonList) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(endPoint);
        try {//from   ww  w .j  a va  2s . co m
            StringEntity entity = new StringEntity(data);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            log.info("data sent : " + data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static byte[] doPostSubmit(String url, List<NameValuePair> params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();
    try {//from w  w  w .j a v  a  2 s  . c o  m
        httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toByteArray(entity);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}