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:com.optimusinfo.elasticpath.cortex.common.Utils.java

/**
 * Get data from the given Cortex URL/*from  www  .j a  v a 2  s.  c  o m*/
 * 
 * @param url
 *            URL of the API
 * @param accessToken
 *            the access token to authenticate the request
 * @param contentType
 *            the content type of the request
 * @param contentTypeString
 * @param authorizationString
 * @param accessTokenInitializer
 *            the string to be used before the access token as per the
 *            guidelines
 * @return the JSON data returned by this navigation task
 */
public static String getJSONFromCortexUrl(String url, String accessToken, String contentType,
        String contentTypeString, String authorizationString, String accessTokenInitializer) {
    try {
        // Input stream
        InputStream objInputStream;
        // JSON String
        String responseJSON;
        // Making HTTP request
        DefaultHttpClient httpClient = new DefaultHttpClient();

        Log.i("GET REQUEST", url);

        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeader(contentTypeString, contentType);

        httpGet.setHeader(authorizationString, accessTokenInitializer + " " + accessToken);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        switch (httpResponse.getStatusLine().getStatusCode()) {
        case Constants.ApiResponseCode.REQUEST_SUCCESSFUL_CREATED:
        case Constants.ApiResponseCode.REQUEST_SUCCESSFUL_UPDATED:
            objInputStream = httpEntity.getContent();
            break;
        case Constants.ApiResponseCode.UNAUTHORIZED_ACCESS:
            return Integer.toString((Constants.ApiResponseCode.UNAUTHORIZED_ACCESS));
        default:
            return Integer.toString(httpResponse.getStatusLine().getStatusCode());
        }
        ;

        // Parse the response to String
        BufferedReader objReader = new BufferedReader(new InputStreamReader(objInputStream, "iso-8859-1"), 8);
        StringBuilder objSb = new StringBuilder();
        String line = null;

        while ((line = objReader.readLine()) != null) {
            objSb.append(line + "\n");
        }
        objInputStream.close();

        // Instantiate the String before setting it to the result
        // string
        responseJSON = new String();
        responseJSON = objSb.toString();

        return responseJSON;
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}

From source file:it.restrung.rest.client.DefaultRestClientImpl.java

/**
 * Performs a GET request enforcing basic auth
 *
 * @param url      the url to be requested
 * @param user     the user/*ww  w  .  j a  va 2s . c om*/
 * @param password the password
 * @param timeout  a request timeout
 * @return the response body as a String
 * @throws APIException
 */
public static String performGet(String url, String user, String password, int timeout, APIDelegate<?> delegate)
        throws APIException {
    Log.d(RestClient.class.getSimpleName(), "GET: " + url);
    String responseBody;
    try {
        DefaultHttpClient httpclient = HttpClientFactory.getClient();
        HttpGet httpget = new HttpGet(url);
        setupTimeout(timeout, httpclient);
        setupCommonHeaders(httpget);
        setupBasicAuth(user, password, httpget);
        handleRequest(httpget, delegate);
        HttpResponse response = httpclient.execute(httpget);
        responseBody = handleResponse(response, delegate);
    } catch (ClientProtocolException e) {
        throw new APIException(e, APIException.UNTRACKED_ERROR);
    } catch (IOException e) {
        throw new APIException(e, APIException.UNTRACKED_ERROR);
    }
    return responseBody;
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static TagNode TagNodeFromURLEx2(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (cookieStore != null) {
        httpclient.setCookieStore(cookieStore);
    }//from   w  w w  . j a v  a2  s  .co m
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);
    if (cookieStore == null) {
        cookieStore = httpclient.getCookieStore();
    }

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    HttpEntity httpEntity = response.getEntity();
    InputStream is = httpEntity.getContent();
    return TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
}

From source file:com.etime.ETimeUtils.java

protected static String getHtmlPageWithProgress(DefaultHttpClient client, String url, ETimeAsyncTask asyncTask,
        int startProgress, int maxProgress, int estimatedPageSize) {
    HttpResponse response;//from  w w  w  .j a v a 2s .co  m
    HttpGet httpGet;
    BufferedReader in = null;
    String page = null;
    int runningSize = 0;
    int progress = startProgress;
    int tempProgress;
    String redirect = null;

    try {
        httpGet = new HttpGet(url);

        response = client.execute(httpGet);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder sb = new StringBuilder("");
        String line;
        String NL = System.getProperty("line.separator");

        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            if (header.getName().equals("Content-Length")) {
                try {
                    estimatedPageSize = Integer.parseInt(header.getValue());
                } catch (Exception e) {
                    Log.w(TAG, e.toString());
                }
            } else if (header.getName().equals("Location")) {
                redirect = header.getValue();
            }
            if (asyncTask != null) {
                progress += 5 / (maxProgress - startProgress);
                asyncTask.publishToProgressBar(progress);
            }
        }
        while ((line = in.readLine()) != null) {
            if (asyncTask != null) {
                runningSize += line.length();
                tempProgress = startProgress + (int) (((double) runningSize / ((double) estimatedPageSize))
                        * (maxProgress - startProgress));
                progress = (progress >= tempProgress ? progress : tempProgress);
                if (progress > maxProgress) { //happens when estimatedPageSize <= runningSize
                    progress = maxProgress;
                }

                asyncTask.publishToProgressBar(progress);
            }
            sb.append(line).append(NL);
        }
        page = sb.toString();

    } catch (Exception e) {
        Log.v(TAG, e.toString());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    if (redirect != null) {
        return redirect;
    }

    return page;
}

From source file:com.tedx.webservices.WebServices.java

public static JSONArray SendHttpPostArray(String URL, JSONObject jsonObjSend) {
    try {/*from  www.ja va 2 s  .co m*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        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();
        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();

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

            return jsonObjRecv;
        }
    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Load json by type.<br>
 *
 * @param activity    - to get context/* w w  w.j a v  a2 s .  c  o m*/
 * @param action      - get or post or s.thing else. Define at top of class
 * @param data        - Parameter
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @param username    - username if sever need to log in
 * @param password    - password if sever need to log in
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void LoadJSONByType(final Activity activity, final int action, final HashMap<String, String> data,
        final String url, final String username, final String password, final APICallBack apiCallBack) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpGet get = null;
                HttpPost post = null;
                HttpResponse response = null;
                String paramString = null;

                ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        BasicNameValuePair value = new BasicNameValuePair(key, data.get(key));
                        list.add(value);
                    }
                }
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);

                DefaultHttpClient client = new DefaultHttpClient(params);

                /**
                 * Select action to do
                 */
                switch (action) {
                case ACTION_GET_JSON:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    response = client.execute(post);
                    break;
                case ACTION_GET_JSON_WITH_AUTH:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    setAuthenticate(client, get, username, password);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON_WITH_AUTH:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    setAuthenticate(client, post, username, password);
                    response = client.execute(post);
                    break;
                }

                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.HttpUtils.java

/**
 * @param config Gerrit Server Configuration.
 * @param url URL to get.//from w  ww .  j  a  v  a  2  s  . c  o m
 * @return httpresponse.
 * @throws IOException if found.
 */
public static HttpResponse performHTTPGet(IGerritHudsonTriggerConfig config, String url) throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL proxyUrl = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
        }
    }

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    HttpResponse execute;
    return httpclient.execute(httpGet);
}

From source file:com.tedx.webservices.WebServices.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
    try {//from   ww  w.j  ava 2  s  .c o  m
        DefaultHttpClient httpclient = new DefaultHttpClient();
        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();
        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();

            // remove wrapping "[" and "]"
            if (resultString.substring(0, 1).contains("["))
                resultString = resultString.substring(1, resultString.length() - 1);

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

            return jsonObjRecv;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:org.apiwatch.util.IO.java

public static void putAPIData(APIScope scope, String format, String encoding, String location, String username,
        String password) throws SerializationError, IOException, HttpException {
    if (URL_RX.matcher(location).matches()) {
        DefaultHttpClient client = new DefaultHttpClient();
        if (username != null && password != null) {
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(username, password));
        }//from   w ww  .  ja v a  2s  .  c  o  m
        HttpPost req = new HttpPost(location);
        StringWriter writer = new StringWriter();
        Serializers.dumpAPIScope(scope, writer, format);
        HttpEntity entity = new StringEntity(writer.toString(), encoding);
        req.setEntity(entity);
        req.setHeader("content-type", format);
        req.setHeader("content-encoding", encoding);
        HttpResponse response = client.execute(req);
        client.getConnectionManager().shutdown();
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new HttpException(response.getStatusLine().getReasonPhrase());
        }
        LOGGER.info("Sent results to URL: " + location);
    } else {
        File dir = new File(location);
        dir.mkdirs();
        File file = new File(dir, "api." + format);
        OutputStream out = new FileOutputStream(file);
        Writer writer = new OutputStreamWriter(out, encoding);
        Serializers.dumpAPIScope(scope, writer, format);
        writer.flush();
        writer.close();
        out.close();
        LOGGER.info("Wrote results to file: " + file);
    }
}

From source file:it.attocchi.utils.HttpClientUtils.java

/**
 * //from w ww. j  a va2  s .  co  m
 * @param url
 *            un url dove scaricare il file
 * @param urlFileNameParam
 *            specifica il parametro nell'url che definisce il nome del
 *            file, se non specificato il nome corrisponde al nome nell'url
 * @param dest
 *            dove salvare il file, se non specificato crea un file
 *            temporaneo
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static File getFile(String url, String urlFileNameParam, File dest)
        throws ClientProtocolException, IOException {

    DefaultHttpClient httpclient = null;
    HttpGet httpget = null;
    HttpResponse response = null;
    HttpEntity entity = null;

    try {
        httpclient = new DefaultHttpClient();

        url = url.trim();

        /* Per prima cosa creiamo il File */
        String name = getFileNameFromUrl(url, urlFileNameParam);
        String baseName = FilenameUtils.getBaseName(name);
        String extension = FilenameUtils.getExtension(name);

        if (dest == null)
            dest = File.createTempFile(baseName + "_", "." + extension);

        /* Procediamo con il Download */
        httpget = new HttpGet(url);
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        if (entity != null) {

            OutputStream fos = null;
            try {
                // var fos = new
                // java.io.FileOutputStream('c:\\temp\\myfile.ext');
                fos = new java.io.FileOutputStream(dest);
                entity.writeTo(fos);
            } finally {
                if (fos != null)
                    fos.close();
            }

            logger.debug(fos);
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        // org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpClient);
        // if (entity != null)
        // EntityUtils.consume(entity);
        //

        try {
            if (httpclient != null)
                httpclient.getConnectionManager().shutdown();
        } catch (Exception ex) {
            logger.error(ex);
        }
    }

    return dest;
}