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.netflix.raigad.utils.SystemUtils.java

public static String runHttpGetCommand(String url) throws Exception {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;//from   ww  w . j a  v  a 2s .c o m
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpGet getRequest = new HttpGet(url);
        getRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(getRequest);

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

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

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

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

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("GET URL API: {} returns: {}", url, 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:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/*www  . j a  v a  2s.  com*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

public static Response<String> putToURL(Context context, GHCredentials apiCredentials, String url,
        Map<String, String> headers, String content) throws NoRouteToHostException, URISyntaxException,
        IOException, ClientProtocolException, AuthenticationException {
    if (!Utils.isInternetConnectionAvailable(context))
        throw new NoRouteToHostException("Network not available");

    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri, apiCredentials);

    HttpPut httpPut = new HttpPut(uri);

    setHeaders(httpPut, headers);/*from   ww w  .j  a v  a 2  s.c  om*/

    if (content != null)
        httpPut.setEntity(new StringEntity(content, "UTF-8"));

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
}

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

/**
 * Performs a POST request to the given url
 *
 * @param url           the url//ww w  .  j a v a 2  s .  c o  m
 * @param user          an optional user for basic auth
 * @param password      an optional password for basic auth
 * @param body          an optional body to send with the request
 * @param file          an optional file that would result in a multipart request
 * @param timeout       the request timeout
 * @param apiPostParams an optional callback to get progress
 * @param delegate      the api delegate that will receive callbacks regarding progress and results
 * @return the response body as a string
 * @throws APIException
 */
public static String performPost(String url, String user, String password, String body, final File file,
        int timeout, APIPostParams apiPostParams, APIDelegate<?> delegate) throws APIException {
    Log.d(RestClient.class.getSimpleName(), "POST: " + url);
    String responseBody;
    try {
        DefaultHttpClient httpclient = HttpClientFactory.getClient();
        HttpPost httppost = new HttpPost(url);
        setupTimeout(timeout, httpclient);
        setupCommonHeaders(httppost);
        setupBasicAuth(user, password, httppost);
        setupRequestBody(httppost, body, apiPostParams, file);
        handleRequest(httppost, delegate);
        HttpResponse response = httpclient.execute(httppost);
        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:com.hybris.mobile.logging.ExceptionHandler.java

public static void submitStackTraces() {
    try {/* w ww  .  j a va2 s  .c  o  m*/
        LoggingUtils.d(LOG_TAG, "Looking for exceptions in: " + RA.FILES_PATH);
        String[] list = searchForStackTraces();
        if (list != null && list.length > 0) {
            LoggingUtils.d(LOG_TAG, "Found " + list.length + " stacktrace(s)");
            for (int i = 0; i < list.length; i++) {
                String filePath = RA.FILES_PATH + "/" + list[i];
                // Extract the version from the filename: "packagename-version-...."
                String version = list[i].split("-")[0];
                LoggingUtils.d(LOG_TAG, "Stacktrace in file '" + filePath + "' belongs to version " + version);
                // Read contents of stacktrace
                StringBuilder contents = new StringBuilder();
                BufferedReader input = new BufferedReader(new FileReader(filePath));
                String line = null;
                String androidVersion = null;
                String phoneModel = null;
                while ((line = input.readLine()) != null) {
                    if (androidVersion == null) {
                        androidVersion = line;
                        continue;
                    } else if (phoneModel == null) {
                        phoneModel = line;
                        continue;
                    }
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }
                input.close();
                String stacktrace;
                stacktrace = contents.toString();
                LoggingUtils.d(LOG_TAG, "Transmitting stack trace: " + stacktrace);
                // Transmit stack trace with POST request
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(RA.URL);
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("package_name", RA.APP_PACKAGE));
                nvps.add(new BasicNameValuePair("package_version", version));
                nvps.add(new BasicNameValuePair("phone_model", phoneModel));
                nvps.add(new BasicNameValuePair("android_version", androidVersion));
                nvps.add(new BasicNameValuePair("stacktrace", stacktrace));
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                httpClient.execute(httpPost);
            }
        }
    } catch (Exception e) {
        LoggingUtils.e(LOG_TAG, "Error submitting stack traces. " + e.getLocalizedMessage(), null);
    } finally {
        String[] list = searchForStackTraces();
        for (int i = 0; i < list.length; i++) {
            File file = new File(RA.FILES_PATH + "/" + list[i]);
            file.delete();
        }
    }
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse patch(TransportTools nuts) throws ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPatch httppatch = new HttpPatch(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httppatch.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }//from  w w  w. j  a v  a2  s.co  m
    }

    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppatch.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppatch.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }

    TransportResponse transportResp = null;
    try {
        httpclient.execute(httppatch);
        //transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale());
    } finally {
        httppatch.releaseConnection();
    }
    return transportResp;

}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static String jobQuery(String msgtype, String job_id, int rating, String driver_id) {

    HttpPost postJob = new HttpPost(HttpHelper.domain + "jobquery.php");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 4900;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient clientJob = new DefaultHttpClient(httpParameters);

    try {/*from w w  w .  j ava 2  s .  co  m*/
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("msgtype", msgtype));
        infoJob.add(new BasicNameValuePair("job_id", job_id));
        infoJob.add(new BasicNameValuePair("rating", Integer.toString(rating)));
        infoJob.add(new BasicNameValuePair("driver_id", driver_id));
        postJob.setEntity(new UrlEncodedFormEntity(infoJob));
        HttpResponse response = clientJob.execute(postJob);

        String result = "done";

        return result;

    } catch (Exception e) {

        return null;
    }

}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse put(TransportTools nuts) throws ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httpput.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }//from w  ww  .  java2 s  .  c  o m
    }

    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httpput.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httpput.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }

    TransportResponse transportResp = null;
    try {
        HttpResponse httpResp = httpclient.execute(httpput);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httpput.releaseConnection();
    }
    return transportResp;

}

From source file:com.mingsoft.util.proxy.Proxy.java

/**
 * get??/*ww  w .jav a 2  s .co  m*/
 * 
 * @param url
 *            ?<br>
 * @param fileUrl
 *            ????<br>
 * @param header
 *            ?Header new Header()<br>
 */
public static void getRandCode(String url, com.mingsoft.util.proxy.Header header, String fileUrl) {
    DefaultHttpClient client = new DefaultHttpClient();

    //log.info("?" + url);
    // get
    HttpGet get = new HttpGet(url);
    // cookie?()
    get.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    Map _headers = header.getHeaders();
    // ?
    if (null != header && _headers.size() > 0) {
        get.setHeaders(Proxy.assemblyHeader(_headers));
    }
    HttpResponse response;
    try {
        response = client.execute(get);

        // ?
        // Header[] h = (Header[]) response.getAllHeaders();
        // for (int i = 0; i < h.length; i++) {
        // Header a = h[i];
        // }

        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        // cookie???cookie
        header.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        int temp = 0;
        // 
        File file = new File(fileUrl);
        // ??
        FileOutputStream out = new FileOutputStream(file);
        while ((temp = in.read()) != -1) {
            out.write(temp);
        }
        in.close();
        out.close();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
}

From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java

protected static HttpResponse doDelete(String resource) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpDelete delete = new HttpDelete(getEndPoint(resource));
    delete.setHeader(AUTH_HEADER);/*  ww  w  .ja  va 2s .com*/
    return client.execute(delete);
}