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:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String xhrRequest(String shrDataString) {
    InputStream is = null;//from w w w. ja  v a  2 s . c om
    String json = null;

    try {
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "shrDataString [" + shrDataString + "]");

        Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString));
        String url = (String) xhrData.get("url");
        String method = (String) xhrData.get("method");
        List headers = (List) xhrData.get("headers");
        URL requestURL = createURL(url);
        URI uri = new URI(requestURL.toString());

        HashMap httpMethods = new HashMap(7);
        httpMethods.put("DELETE", new HttpDelete(uri));
        httpMethods.put("GET", new HttpGet(uri));
        httpMethods.put("HEAD", new HttpHead(uri));
        httpMethods.put("OPTIONS", new HttpOptions(uri));
        httpMethods.put("POST", new HttpPost(uri));
        httpMethods.put("PUT", new HttpPut(uri));
        httpMethods.put("TRACE", new HttpTrace(uri));
        HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase());

        if (request.equals(null)) {
            throw new Error("SYNTAX_ERR");
        }

        for (Object header : headers) {
            StringTokenizer st = new StringTokenizer((String) header, ":");
            String name = st.nextToken();
            String value = st.nextToken();
            request.addHeader(name, value);
        }

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Map headerMap = new HashMap();

        HeaderIterator headerIter = response.headerIterator();

        while (headerIter.hasNext()) {
            Header header = headerIter.nextHeader();
            headerMap.put(header.getName(), header.getValue());
        }

        int status = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().toString();

        is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        Map m = new HashMap();
        m.put("status", new Integer(status));
        m.put("statusText", statusText);
        m.put("responseText", sb.toString());
        m.put("headers", headerMap.toString());
        StringWriter w = new StringWriter();
        JSONSerializer.serialize(w, m);
        json = w.toString();
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]");
    } catch (Throwable e) {
        logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "Failed request for [" + shrDataString + "]", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    return json;
}

From source file:com.ajah.http.Http.java

private static HttpEntity internalGet(final URI uri)
        throws IOException, ClientProtocolException, NotFoundException, UnexpectedResponseCode {
    final HttpClient httpclient = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(uri);
    final HttpResponse response = httpclient.execute(httpget);
    if (response.getStatusLine().getStatusCode() == 200) {
        final HttpEntity entity = response.getEntity();
        return entity;
    } else if (response.getStatusLine().getStatusCode() == 404) {
        throw new NotFoundException(
                response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
    } else {//ww w .  j  av a2 s  .  c o  m
        throw new UnexpectedResponseCode(
                response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
    }
}

From source file:language_engine.HttpUtils.java

public static String doHttpPost(String url, List<NameValuePair> params) {
    try {/*w w  w.  ja  va  2s. c o m*/
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.keycloak.adapters.cloned.HttpAdapterUtils.java

public static MultivaluedHashMap<String, KeyInfo> downloadKeysFromSamlDescriptor(HttpClient client,
        String descriptorUrl) throws HttpClientAdapterException {
    try {// www  . ja  v  a2s.  co m
        HttpGet httpRequest = new HttpGet(descriptorUrl);
        HttpResponse response = client.execute(httpRequest);
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw new HttpClientAdapterException("Unexpected status = " + status);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new HttpClientAdapterException("There was no entity.");
        }

        MultivaluedHashMap<String, KeyInfo> res;
        try (InputStream is = entity.getContent()) {
            res = extractKeysFromSamlDescriptor(is);
        }

        EntityUtils.consumeQuietly(entity);

        return res;
    } catch (IOException | ParsingException e) {
        throw new HttpClientAdapterException("IO error", e);
    }
}

From source file:org.phpmaven.pear.library.impl.Helper.java

/**
 * Returns the text file contents./*from  w  w w  .ja  va 2s .  c  o  m*/
 * @param uri URI of the resource.
 * @return the files content.
 * @throws IOException thrown on errors.
 */
public static String getTextFileContents(String uri) throws IOException {
    // is it inside the local filesystem?
    if (uri.startsWith("file://")) {
        final File channelFile = new File(uri.substring(7));

        final String lineSep = System.getProperty("line.separator");
        final BufferedReader br = new BufferedReader(new FileReader(channelFile));
        String nextLine = "";
        final StringBuffer sb = new StringBuffer();
        while ((nextLine = br.readLine()) != null) {
            sb.append(nextLine);
            sb.append(lineSep);
        }
        br.close();
        return sb.toString();
    }

    // try http connection
    final HttpClient client = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(uri);
    final HttpResponse response = client.execute(httpget);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Invalid http status: " + response.getStatusLine().getStatusCode() + " / "
                + response.getStatusLine().getReasonPhrase());
    }
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new IOException("Empty response.");
    }
    return EntityUtils.toString(entity);
}

From source file:org.jorge.lolin1.io.net.HTTPServices.java

public static InputStream performGetRequest(String uri, String locale)
        throws IOException, URISyntaxException, ServerIsCheckingException {
    HttpResponse response;//from   ww w .  j a  v  a 2  s.c o  m

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(params, LoLin1Utils.getLocaleCharset(locale).name());
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI(uri));
    response = client.execute(request);
    if (response.getStatusLine().getStatusCode() == 409) {
        throw new ServerIsCheckingException();
    } else {
        return response.getEntity().getContent();
    }
}

From source file:org.eclipse.json.http.HttpHelper.java

public static JsonValue makeRequest(String url) throws IOException {
    long startTime = 0;
    HttpClient httpClient = new DefaultHttpClient();
    try {//  w  w w  .  j  ava2 s  .c  om
        // Post JSON Tern doc
        HttpGet httpGet = new HttpGet(url);
        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) {
            // node.js server throws error
            /*
             * String message = IOUtils.toString(in); if
             * (StringUtils.isEmpty(message)) { throw new
             * TernException(statusLine.toString()); } throw new
             * TernException(message);
             */
        }

        try {
            JsonValue response = JsonValue.readFrom(new InputStreamReader(in));
            return response;
        } catch (ParseException e) {
            throw new IOException(e);
        }
    } catch (Exception e) {
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new IOException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:fm.krui.kruifm.JSONFunctions.java

public static JSONObject getJSONObjectFromURL(String url) {
    InputStream is = null;/*  w w  w . ja  v  a2  s.co  m*/
    String result = "";
    JSONObject jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httppost = new HttpGet(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e(TAG, "Error in http connection " + e.toString());
    }

    //convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());
    }

    return jArray;
}

From source file:fm.krui.kruifm.JSONFunctions.java

public static JSONArray getJSONArrayFromURL(String url) {
    InputStream is = null;//from   w  w w .ja va 2 s  .  c  om
    String result = "";
    JSONArray jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httppost = new HttpGet(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e(TAG, "Error in http connection " + e.toString());
    }

    //convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONArray(result);
    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());
    }

    return jArray;
}

From source file:com.github.restdriver.clientdriver.integration.VerifyWithinTest.java

private static void hitThat(String url) {
    try {/*from ww  w.  j a v  a 2s  . c  om*/
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        client.execute(get);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}