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:org.escidoc.browser.elabsmodul.service.ELabsService.java

private static boolean sendStartRequest(final List<String[]> propertyList) {
    LOG.info("Service> Send configuration to start...");

    boolean hasError = false;

    Preconditions.checkNotNull(propertyList, "Config list is null");
    final String configURLPart = "/configuration";

    for (final String[] configurationArray : propertyList) {
        String esyncEndpoint = configurationArray[0];
        LOG.debug("Service> sending start request for " + esyncEndpoint);
        while (esyncEndpoint.endsWith("/")) {
            esyncEndpoint = esyncEndpoint.substring(0, esyncEndpoint.length() - 1);
        }/*from  w  w w . ja  v  a  2s .  c  om*/

        if (!esyncEndpoint.endsWith(configURLPart)) {
            esyncEndpoint = esyncEndpoint + configURLPart;
        }

        try {
            LOG.debug("Service> called HttpClient.");
            // FIXME set proxy
            final DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.setKeepAliveStrategy(null);
            final HttpPut putMethod = new HttpPut(esyncEndpoint);
            putMethod.setEntity(new StringEntity(configurationArray[1], HTTP.UTF_8));
            final HttpResponse response = httpClient.execute(putMethod);
            final StatusLine statusLine = response.getStatusLine();
            if (isNotSuccessful(statusLine.getStatusCode())) {
                LOG.error("Service> wrong method call: " + statusLine.getReasonPhrase());
                hasError = true;
            } else {
                LOG.info("Service> configuration is successfully sent!");
            }
        } catch (final UnsupportedEncodingException e) {
            LOG.error("Service> UnsupportedEncodingException: " + e.getMessage());
            hasError = true;
            continue;
        } catch (final ClientProtocolException e) {
            LOG.error("Service> ClientProtocolException: " + e.getMessage());
            hasError = true;
            continue;
        } catch (final IOException e) {
            LOG.error("Service> IOException: " + e.getMessage());
            hasError = true;
            continue;
        }
    }
    return hasError;
}

From source file:com.abombrecords.amt_unlocker.AMT_Unlocker.java

public static boolean UnlockDoor(String Username, String Password, String DoorPIN) throws Exception {
    boolean bSuccess = false;

    //Log.d(LogTag, "Login");   
    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httpost = new HttpPost("http://acemonstertoys.org/node?destination=node");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("op", "Log in"));
    nvps.add(new BasicNameValuePair("name", Username));
    nvps.add(new BasicNameValuePair("pass", Password));
    nvps.add(new BasicNameValuePair("openid.return_to",
            "http://acemonstertoys.org/openid/authenticate?destination=node"));
    nvps.add(new BasicNameValuePair("form_id", "user_login_block"));
    nvps.add(new BasicNameValuePair("form_build_id", "form-4d6478bc67a79eda5e36c01499ba4c88"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpclient.execute(httpost);
    HttpEntity entity = response.getEntity();

    //Log.d(LogTag, "Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();/*from ww w .j a va2 s.  co  m*/
    }

    //Log.d(LogTag, "Post Login cookies:");
    // look for drupal_uid and fail out if it isn't there
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        //Log.d(LogTag, "None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            //Log.d(LogTag, "- " + cookies.get(i).toString());

            if (cookies.get(i).getName().equals("drupal_uid")) {
                bSuccess = true;
            }
        }
    }

    if (bSuccess) {
        HttpPost httpost2 = new HttpPost("http://acemonstertoys.org/membership");

        List<NameValuePair> nvps2 = new ArrayList<NameValuePair>();
        nvps2.add(new BasicNameValuePair("doorcode", DoorPIN));
        nvps2.add(new BasicNameValuePair("forceit", "Open Door"));

        httpost2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

        response = httpclient.execute(httpost2);
        entity = response.getEntity();

        //Log.d(LogTag, "Unlock form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
    }

    httpclient.getConnectionManager().shutdown();

    return bSuccess;
}

From source file:com.github.ajasmin.telususageandroidwidget.TelusReportFetcher.java

private static void logIn(DefaultHttpClient httpclient, PreferencesData prefs)
        throws NetworkErrorException, InvalidCredentialsException {
    try {/*from w  ww.  j  a  v  a 2 s.c  o  m*/
        final String url = "https://mobile.telus.com/login.htm";
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("username", prefs.email));
        formparams.add(new BasicNameValuePair("password", prefs.password));
        formparams.add(new BasicNameValuePair("_rememberMe", "on"));
        formparams.add(new BasicNameValuePair("forwardAction", "/index.htm?lang=en"));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(entity);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String str = EntityUtils.toString(responseEntity);
        if (str.contains("The email or password you entered is invalid.")) {
            throw new InvalidCredentialsException();
        }
    } catch (IOException e) {
        throw new NetworkErrorException("Error logging in", e);
    }
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPutCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;/*from   w  w w  .ja v a2 s.  c  om*/
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPut putRequest = new HttpPut(url);
        putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        putRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(putRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute PUT URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}

From source file:com.pindroid.client.PinboardApi.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * /*  ww  w .  ja va2 s.c  o  m*/
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 * @throws  
 */
public static String pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(AUTH_TOKEN_URI);
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

            final HttpEntity entity = resp.getEntity();

            InputStream instream = entity.getContent();
            SaxTokenParser parser = new SaxTokenParser(instream);
            PinboardAuthToken token = parser.parse();
            instream.close();

            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
                Log.v(TAG, "AuthToken: " + token.getToken());
            }

            return token.getToken();
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return null;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return null;
    } catch (ParseException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "ParseException when getting authtoken", e);
        }
        return null;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:com.cbtec.eliademyutils.EliademyUtils.java

public static String serviceCall(String data, String webService, String token, String serviceClient) {

    String retval = null;/* ww w  .  j a v a2s.  c o  m*/
    Log.d("EliademyUtils", "Service: " + data + " Service: " + webService);

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        if (data.toString().length() > 0) {
            JSONObject jsObj = new JSONObject(data.toString());
            nameValuePairs.addAll(nameValueJson(jsObj, ""));
        }
        nameValuePairs.add(new BasicNameValuePair("wstoken", token));
        nameValuePairs.add(new BasicNameValuePair("wsfunction", webService));
        nameValuePairs.add(new BasicNameValuePair("moodlewsrestformat", "json"));

        HttpPost httppost = new HttpPost(serviceClient + "/webservice/rest/server.php?");

        Log.d("EliademyUtils", nameValuePairs.toString());
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            StringBuilder jsonStr = new StringBuilder();
            InputStream iStream = entity.getContent();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iStream));
            String jpart;
            while ((jpart = bufferReader.readLine()) != null) {
                jsonStr.append(jpart);
            }
            iStream.close();
            return jsonStr.toString();
        }
    } catch (Exception e) {
        Log.e("EliademyUtils", "exception", e);
        return retval;
    }
    return retval;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout,
        Boolean pRedirect) throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    if (!pRedirect) {
        HttpClientParams.setRedirecting(httpParams, false);
    }//from w  w w .  j  a  v a 2 s.c om
    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout)
        throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    HttpClientParams.setRedirecting(httpParams, true);

    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override/*from  w  ww.j  a  v a  2s .co  m*/
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketTimeoutException e) {
        e = new SocketTimeoutException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

From source file:com.deliciousdroid.client.DeliciousApi.java

/**
 * Performs an api call to Delicious's http based api methods.
 * //from  www .j  a v  a 2s . c o  m
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 */
private static InputStream DeliciousApiCall(String url, TreeMap<String, String> params, Account account,
        Context context) throws IOException, AuthenticationException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = null;

    try {
        authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, false);
    } catch (OperationCanceledException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "DeliciousDroid");
    post.setHeader("Accept-Encoding", "gzip");

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();
    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, authtoken);
    provider.setCredentials(SCOPE, credentials);

    client.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException();
    } else {
        throw new IOException();
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {// w  w  w  .  j  a  v a2  s.  co  m
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}