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:core.RESTCalls.RESTPost.java

public static InputStream httpPostResponse(String urlStr) throws Exception {

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(urlStr);

    HttpResponse response = client.execute(post);

    return response.getEntity().getContent();
}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static Bitmap getImage(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    Log.d("SUSEConferences", "Get: " + url);
    HttpResponse response = client.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }/*from w  ww.jav  a2  s . co m*/
                entity.consumeContent();
            }
        } else {
            throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
        }
    } else {
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }
}

From source file:org.wso2.api.client.restcalls.StoreAPIInvoker.java

public static String loginToStore(HttpClient httpClient) throws IOException {
    HttpPost storeLoginRequest = new HttpPost(APIDownloaderConstant.LOGIN_API_CALL);
    HttpResponse storeLoginResponse = httpClient.execute(storeLoginRequest);

    for (Header header : storeLoginResponse.getAllHeaders()) {
        if (header.getName().equals("Set-Cookie")) {
            return header.getValue().split(";", 2)[0];
        }//from ww w. j  a  va  2 s.c  om
    }
    return null;
}

From source file:com.alta189.cyborg.commandkit.util.HttpUtil.java

public static String hastebin(String data) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(hastebin);

    try {/*w  ww.j a v  a  2 s.  c o m*/
        post.setEntity(new StringEntity(data));

        HttpResponse response = client.execute(post);

        String result = EntityUtils.toString(response.getEntity());
        return "http://hastebin.com/" + new Gson().fromJson(result, Hastebin.class).getKey();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:realizer.com.schoolgenieparent.ServerUtilities.java

private static StringBuilder post(String regID, String EmpId) {
    //String my = "http://104.217.254.180/RestWCF/svcEmp.svc/registerDevice/" + EmpId + "/" + regID;
    SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String did = sharedpreferences.getString("DWEVICEID", "");

    //String my = "http://192.168.1.14/SJRestWCF/registerDevice/" + EmpId + "/" + regID;
    String my = Config.URL + "RegisterStudentDevice/" + EmpId + "/" + did + "/" + regID;
    Log.d("GCMDID", my);
    builder = new StringBuilder();
    HttpGet httpGet = new HttpGet(my);
    HttpClient client = new DefaultHttpClient();
    try {//from www .j a va  2  s  .  c  om
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();

        int statusCode = statusLine.getStatusCode();
        Log.d("GCMSTATUS", "" + statusCode);
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("Error", "Failed to Login");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().closeExpiredConnections();
        client.getConnectionManager().shutdown();
    }

    return builder;
}

From source file:tr.edu.gsu.nerwip.tools.freebase.FbIdTools.java

/**
 * This method takes the title of a Wikipedia page,
 * and retrieves its Freebase id.//from w w w.  ja v  a  2  s  . c o m
 * 
 * @param wikipediaTitle
 *       Title of the Wikipedia article.
 * @return
 *       A String describing a the FB id.
 * 
 * @throws IOException 
 *       Problem while retrieving the FB types.
 * @throws ClientProtocolException 
 *       Problem while retrieving the FB types.
 * @throws org.json.simple.parser.ParseException 
 *       Problem while retrieving the FB types.
 * @throws ParseException
 *       Problem while retrieving the FB types.
 */
public static String getId(String wikipediaTitle)
        throws ClientProtocolException, IOException, ParseException, org.json.simple.parser.ParseException {
    logger.increaseOffset();
    String result = null;

    // possibly get result from cache
    if (FbCommonTools.cache) {
        if (wp2fb == null)
            wp2fb = new FbCache(FileNames.FI_IDS);
        result = wp2fb.getValue(wikipediaTitle);
    }

    if (result == null) { // set Freebase query using the MQL-read API
        String query = "[{ \"name\": null, " + "\"id\": null, " + "\"key\": "
                + "[{ \"namespace\": \"/wikipedia/en\", " + // TODO this part would be different for another source than WP
                "\"value\": \"" + wikipediaTitle + "\" }] }]";
        String url = FbCommonTools.URL_MQL + "?key=" + FbCommonTools.getKey() + "&query="
                + URLEncoder.encode(query, "UTF-8");

        logger.log(query);
        logger.log(url);

        // get Freebase answer
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpclient.execute(request);

        // builds object from answer
        JSONParser parser = new JSONParser();
        HttpEntity entity = response.getEntity();
        String str = EntityUtils.toString(entity);
        JSONObject jsonData = (JSONObject) parser.parse(str);
        JSONArray answer = (JSONArray) jsonData.get("result");

        // extract types from the answer
        if (answer != null) {
            for (Object object : answer) { // process id
                result = (String) ((JSONObject) object).get("id");
            }
        }

        // possibly cache the result
        if (FbCommonTools.cache) {
            if (result != null)
                wp2fb.putValue(wikipediaTitle, result);
        }
    }

    logger.decreaseOffset();
    return result;
}

From source file:com.foundationdb.http.HttpMonitorVerifyIT.java

private static int openRestURL(HttpClient client, String userInfo, int port, String path) throws Exception {
    URI uri = new URI("http", userInfo, "localhost", port, path, null, null);
    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    int code = response.getStatusLine().getStatusCode();
    EntityUtils.consume(response.getEntity());
    return code;/*from   w  w  w  .  j  a  v a  2s  .c o m*/
}

From source file:com.meltmedia.cadmium.cli.StatusCommand.java

/**
 * Retrieves the status of a Cadmium site into a {@link Status} Object.
 * /*w  ww .j a  v  a 2s  .  c o  m*/
 * @param site The site uri of the Cadmium site to get the status from.
 * @param token The Github API token used for authenticating the request.
 * @return
 * @throws Exception
 */
public static Status getSiteStatus(String site, String token) throws Exception {
    HttpClient client = httpClient();

    HttpGet get = new HttpGet(site + StatusCommand.JERSEY_ENDPOINT);
    addAuthHeader(token, get);

    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    if (entity.getContentType().getValue().equals(MediaType.APPLICATION_JSON)) {
        String responseContent = EntityUtils.toString(entity);
        return new Gson().fromJson(responseContent, new TypeToken<Status>() {
        }.getType());
    }
    return null;
}

From source file:it.polimi.brusamentoceruti.moviebookrest.boundary.JsonRequest.java

public static JSONObject doQuery(String Url) throws JSONException, IOException {
    String responseBody = null;/* w  ww  .  ja  v a  2s  .  c o  m*/
    HttpGet httpget;
    HttpClient httpClient = new DefaultHttpClient();
    try {
        httpget = new HttpGet(Url);
    } catch (IllegalArgumentException iae) {
        return null;
    }

    HttpResponse response = httpClient.execute(httpget);
    InputStream contentStream = null;
    try {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null) {
            throw new IOException(String.format("Unable to get a response from server"));
        }
        int statusCode = statusLine.getStatusCode();
        if (statusCode < 200 && statusCode >= 300) {
            throw new IOException(
                    String.format("OWM server responded with status code %d: %s", statusCode, statusLine));
        }
        /* Read the response content */
        HttpEntity responseEntity = response.getEntity();
        contentStream = responseEntity.getContent();
        Reader isReader = new InputStreamReader(contentStream);
        int contentSize = (int) responseEntity.getContentLength();
        if (contentSize < 0)
            contentSize = 8 * 1024;
        StringWriter strWriter = new StringWriter(contentSize);
        char[] buffer = new char[8 * 1024];
        int n = 0;
        while ((n = isReader.read(buffer)) != -1) {
            strWriter.write(buffer, 0, n);
        }
        responseBody = strWriter.toString();
        contentStream.close();
    } catch (IOException e) {
        throw e;
    } catch (RuntimeException re) {
        httpget.abort();
        throw re;
    } finally {
        if (contentStream != null)
            contentStream.close();
    }
    return new JSONObject(responseBody);
}

From source file:language_engine.HttpUtils.java

public static String doHttpPost(String url, String xmlBody, Header[] headers) {
    try {//ww w .  j a  v  a  2 s  .c  om
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeaders(headers);
        httpPost.setEntity(new StringEntity(xmlBody, "UTF-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        return StreamUtil.readText(resp.getEntity().getContent(), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}