Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler.

Prototype

BasicResponseHandler

Source Link

Usage

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

protected String simpleCall(HttpRequestBase method) {
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return this.call(method, responseHandler, false);
}

From source file:com.comcast.dawg.pound.DawgPoundIT.java

/**
 * This method tests the @link{DawgPound#reserve()} API with invalid id, and verifies that the
 * response is false./*from   w  w  w . j av a  2  s.c o  m*/
 */
@Test(groups = "rest")
public void reserveWithInvalidIdTest() throws ClientProtocolException, IOException {
    String token = "xyz";
    long exp = System.currentTimeMillis() + RESERVE_EXPIRATION_TIME_OFFSET;
    String expiration = String.valueOf(exp);
    String url = BASE_URL + "reserve/override/" + token + "/" + invalidDeviceId + "/" + expiration;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpclient.execute(httppost, responseHandler);
    Assert.assertNotNull(responseBody);
    Assert.assertTrue(responseBody.contains("false"));
}

From source file:fast.servicescreen.server.RequestServiceImpl.java

@Override
public String sendHttpRequest_PUT(String url, HashMap<String, String> headers, String body) {
    //create client and method appending to url
    DefaultHttpClient httpclient_PUT = new DefaultHttpClient();
    httpput = new HttpPut(url);

    //add all headers
    if (headers != null) {
        for (Iterator<String> iterator = headers.keySet().iterator(); iterator.hasNext();) {
            String tmpKey = (String) iterator.next();
            String tmpVal = headers.get(tmpKey);
            httpput.addHeader(tmpKey, tmpVal);
        }// w w  w  .jav  a2s .  c  om
    }

    // Create response handler
    responseHandler = new BasicResponseHandler();

    try {
        // send the POST request
        responseBody = httpclient_PUT.execute(httpput, responseHandler);
    } catch (Exception e) {
        e.printStackTrace();
        responseBody = "-1";
    }
    return responseBody;
}

From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java

private void processPictureWhenReady(final String picturePath) {
    final File pictureFile = new File(picturePath);
    //Map<String, String > result = new HashMap<String,String>();

    if (pictureFile.exists()) {
        // The picture is ready; process it.
        Bitmap imageBitmap = null;/*w w  w .j  a  v  a  2s .com*/
        try {
            //               Bundle extras = data.getExtras();
            //               imageBitmap = (Bitmap) extras.get("data");
            FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file
            imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis);

            if (imageBitmap != null) {
                Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false);
                if (lScaledBitmap != null) {
                    imageBitmap.recycle();
                    imageBitmap = null;

                    ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream();
                    lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes);
                    lScaledBitmap.recycle();
                    lScaledBitmap = null;

                    byte[] lImageByteArray = lImageBytes.toByteArray();

                    HashMap<String, String> lValuePairs = new HashMap<String, String>();
                    lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT));
                    lValuePairs.put("compressionLevel", "30");
                    lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA");
                    lValuePairs.put("documentHints", "");
                    lValuePairs.put("dataReturnLevel", "15");
                    lValuePairs.put("returnImageType", "1");
                    lValuePairs.put("rotateImage", "0");
                    lValuePairs.put("data1", "");
                    lValuePairs.put("data2", "");
                    lValuePairs.put("data3", "");
                    lValuePairs.put("data4", "");
                    lValuePairs.put("data5", "");
                    lValuePairs.put("userName", "zbroyan@miteksystems.com");
                    lValuePairs.put("password", "google1");
                    lValuePairs.put("phoneKey", "1");
                    lValuePairs.put("orgName", "MobileImagingOrg");

                    String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs);

                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    //                        mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R)
                    HttpPost mHttpPost = new HttpPost();

                    mHttpPost.setHeader("User-Agent", "UCSD Team");
                    mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8");
                    //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction"));
                    mHttpPost.setURI(
                            URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx"));

                    StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8);
                    se.setContentType("text/xml; charset=UTF-8");
                    mHttpPost.setEntity(se);
                    HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext());

                    String responseString = new BasicResponseHandler().handleResponse(mResponse);
                    parseXML(responseString);

                    //Todo: this is test code. Need to be implemented
                    //result = parseXML(testStr);
                    Log.i("test", "test:" + " " + responseString);
                    Log.i("test", "test: " + " " + map.size());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // this part will be relocated in order to let the the server process picture
        if (map.size() == 0) {
            Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class);
            display.putExtra("result", (java.io.Serializable) iQAMsg);
            startActivity(display);
        } else {
            Intent display = new Intent(getApplicationContext(), DisplayInfo.class);
            display.putExtra("result", (java.io.Serializable) map);
            startActivity(display);

        }
    } else {
        // The file does not exist yet. Before starting the file observer, you
        // can update your UI to let the user know that the application is
        // waiting for the picture (for example, by displaying the thumbnail
        // image and a progress indicator).

        final File parentDirectory = pictureFile.getParentFile();
        FileObserver observer = new FileObserver(parentDirectory.getPath(),
                FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
            // Protect against additional pending events after CLOSE_WRITE
            // or MOVED_TO is handled.
            private boolean isFileWritten;

            @Override
            public void onEvent(int event, final String path) {
                if (!isFileWritten) {
                    // For safety, make sure that the file that was created in
                    // the directory is actually the one that we're expecting.
                    File affectedFile = new File(parentDirectory, path);
                    isFileWritten = affectedFile.equals(pictureFile);

                    if (isFileWritten) {
                        stopWatching();
                        // Now that the file is ready, recursively call
                        // processPictureWhenReady again (on the UI thread).
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new LongOperation().execute(picturePath);
                            }
                        });
                    }
                }
            }
        };
        observer.startWatching();

    }

}

From source file:com.nexmo.insight.sdk.NexmoInsightClient.java

public InsightResult request(final String number, final String callbackUrl, final String[] features,
        final long callbackTimeout, final String callbackMethod, final String clientRef, final String ipAddress)
        throws IOException, SAXException {
    if (number == null || callbackUrl == null)
        throw new IllegalArgumentException("number and callbackUrl parameters are mandatory.");
    if (callbackTimeout >= 0 && (callbackTimeout < 1000 || callbackTimeout > 30000))
        throw new IllegalArgumentException("callback timeout must be between 1000 and 30000.");

    log.debug("HTTP-Number-Insight Client .. to [ " + number + " ] ");

    List<NameValuePair> params = new ArrayList<>();

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("number", number));
    params.add(new BasicNameValuePair("callback", callbackUrl));

    if (features != null)
        params.add(new BasicNameValuePair("features", strJoin(features, ",")));

    if (callbackTimeout >= 0)
        params.add(new BasicNameValuePair("callback_timeout", String.valueOf(callbackTimeout)));

    if (callbackMethod != null)
        params.add(new BasicNameValuePair("callback_method", callbackMethod));

    if (ipAddress != null)
        params.add(new BasicNameValuePair("ip", ipAddress));

    if (clientRef != null)
        params.add(new BasicNameValuePair("client_ref", clientRef));

    String inshightBaseUrl = this.baseUrl + PATH_INSIGHT;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST or GET method and execute to submit the request
    String response = null;//from w ww .jav  a  2  s  . c  o m
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(inshightBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = inshightBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new InsightResult(InsightResult.STATUS_COMMS_FAILURE, null, null, 0, 0,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"lookup".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseInsightResult(root);
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * http delete/*from w  w w.  j  ava2  s  . c om*/
 * 
 * @param url
 *            URL
 * @return JSON
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String delete(String url) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpDelete httpget = new HttpDelete(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        return httpclient.execute(httpget, responseHandler);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:imageLines.ImageHelpers.java

public static Boolean checkImageHeader(String imageURLString, String uname, String pass)
        throws ClientProtocolException {

    /*/*from  ww  w. ja  va 2 s  .c o  m*/
    URLConnection conn=imageURL.openConnection();
    String userPassword=user+":"+ pass;
    String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
    conn.setRequestProperty ("Authorization", "Basic " + encoding);*/
    DefaultHttpClient httpclient = new DefaultHttpClient();

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(uname, pass));
    HttpHead head = new HttpHead(imageURLString);
    //HttpGet httpget = new HttpGet(imageURLString);
    System.out.println("executing head request" + head.getRequestLine());

    HttpResponse response;
    try {
        response = httpclient.execute(head);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200 || code == 304)
            return true;
    } catch (IOException ex) {
        Logger.getLogger(ImageHelpers.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;

}

From source file:com.xorcode.andtweet.net.ConnectionOAuth.java

/**
 * Universal method for several Timelines...
 * //  w  w  w.  j a  v a  2s.  co m
 * @param url URL predefined for this timeline
 * @param sinceId
 * @param maxId
 * @param limit
 * @param page
 * @return
 * @throws ConnectionException
 */
private JSONArray getTimeline(String url, long sinceId, long maxId, int limit, int page)
        throws ConnectionException {
    setSinceId(sinceId);
    setLimit(limit);

    boolean ok = false;
    JSONArray jArr = null;
    try {
        Uri sUri = Uri.parse(url);
        Uri.Builder builder = sUri.buildUpon();
        if (getSinceId() != 0) {
            builder.appendQueryParameter("since_id", String.valueOf(getSinceId()));
        } else if (maxId != 0) { // these are mutually exclusive
            builder.appendQueryParameter("max_id", String.valueOf(maxId));
        }
        if (getLimit() != 0) {
            builder.appendQueryParameter("count", String.valueOf(getLimit()));
        }
        if (page != 0) {
            builder.appendQueryParameter("page", String.valueOf(page));
        }
        HttpGet get = new HttpGet(builder.build().toString());
        mConsumer.sign(get);
        String response = mClient.execute(get, new BasicResponseHandler());
        jArr = new JSONArray(response);
        ok = (jArr != null);
    } catch (NullPointerException e) {
        // It looks like a bug in the library, but we have to catch it 
        Log.e(TAG, "NullPointerException was caught, URL='" + url + "'");
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ConnectionException(e.getLocalizedMessage());
    }
    if (MyLog.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "getTimeline '" + url + "' " + (ok ? "OK, " + jArr.length() + " statuses" : "FAILED"));
    }
    return jArr;
}

From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.java

/**
 * This methods extracts the number of machines running gs-agents using the rest admin api
 *
 * @param machinesRestAdminUrl//from  www.  j a  va  2  s .  com
 * @return number of machines running gs-agents
 * @throws IOException
 * @throws java.net.URISyntaxException
 */
protected static int getNumberOfMachines(URL machinesRestAdminUrl) throws IOException, URISyntaxException {
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(machinesRestAdminUrl.toURI());
    try {
        String json = client.execute(httpGet, new BasicResponseHandler());
        Matcher matcher = Pattern.compile("\"Size\":\"([0-9]+)\"").matcher(json);
        if (matcher.find()) {
            String rawSize = matcher.group(1);
            int size = Integer.parseInt(rawSize);
            return size;
        } else {
            return 0;
        }
    } catch (Exception e) {
        return 0;
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:ddf.security.samlp.impl.LogoutMessageImpl.java

@Override
public String sendSamlLogoutRequest(LogoutRequest request, String targetUri, boolean isSoap,
        @Nullable Cookie cookie) throws IOException, WSSecurityException {
    XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage(request) : request;

    Element requestElement = getElementFromSaml(xmlObject);
    String requestMessage = DOM2Writer.nodeToString(requestElement);
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(targetUri);
        post.addHeader("Cache-Control", "no-cache, no-store");
        post.addHeader("Pragma", "no-cache");
        post.addHeader("SOAPAction", SAML_SOAP_ACTION);

        post.addHeader("Content-Type", "application/soap+xml");

        post.setEntity(new StringEntity(requestMessage, "utf-8"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        BasicHttpContext context = new BasicHttpContext();
        if (cookie != null) {
            BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
            basicClientCookie.setDomain(cookie.getDomain());
            basicClientCookie.setPath(cookie.getPath());

            BasicCookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(basicClientCookie);
            context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
        }/*from w w  w .  j  a v a2s  . c  om*/

        return httpClient.execute(post, responseHandler, context);
    }
}