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, final HttpContext context)
        throws IOException, ClientProtocolException 

Source Link

Usage

From source file:org.qe4j.web.OpenSeleniumGrid.java

/**
 * Extracts the grid node address from the web driver session
 *
 * @return the address of the grid node web driver is connected to
 * @throws JSONException/*  w w  w .j a  v  a 2 s . com*/
 * @throws IOException
 * @throws ClientProtocolException
 *
 * @return grid node address
 */
public static String getNodeAddress(OpenWebDriver awd)
        throws JSONException, ClientProtocolException, IOException {
    if (awd.isLocal()) {
        return "127.0.0.1";
    }

    String gridUrl = awd.getGridUrl();

    // splitting up grid url (e.g. http://174.129.55.44:4444/wd/hub)
    String[] address = gridUrl.split("/")[2].split(":");
    String hostname = address[0];
    int port = new Integer(address[1]);
    HttpHost host = new HttpHost(hostname, port);

    // call the test session API to get the node data
    DefaultHttpClient client = new DefaultHttpClient();
    SessionId sessionId = ((RemoteWebDriver) awd.getWebDriver()).getSessionId();
    URL testSessionApi = new URL(
            "http://" + hostname + ":" + port + "/grid/api/testsession?session=" + sessionId);
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
            testSessionApi.toExternalForm());
    HttpResponse response = client.execute(host, request);

    JSONObject object = new JSONObject(EntityUtils.toString(response.getEntity()));
    String proxy = object.getString("proxyId");
    log.debug("found proxy [{}] in selenium grid test session", proxy);
    String gridNodeAddress = proxy.split("//")[1].split(":")[0];

    return gridNodeAddress;
}

From source file:com.batontouch.facebook.SessionStore.java

private static void FacebookServerLogin(String token) {
    Log.d("my", token);
    HashMap<String, String> sessionTokens = null;
    mPreferences = mcontext.getSharedPreferences("CurrentUser", mcontext.MODE_PRIVATE);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(Global.FacebookSendToken + token + "&regid=" + Global.gcm_regid);

    get.setHeader("Accept", "application/vnd.batontouch." + Global.version);

    String response = null;/*from   w  w  w  .jav  a  2s  .co  m*/
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(get, responseHandler);
    } catch (ClientProtocolException e) {
        Log.e("my", e.getClass().getName() + e.getMessage() + " clpt");
    } catch (IOException e) {
        Log.e("my", e.getClass().getName() + e.getMessage() + " IO");
    } catch (Exception e) {
        Log.e("my", e.getClass().getName() + e.getMessage() + " exception");
    }

    ParsedLoginDataSet parsedLoginDataSet = new ParsedLoginDataSet();
    try {
        sessionTokens = parseToken(response);
    } catch (Exception e) {
        Log.e("my", e.getClass().getName() + e.getMessage() + "5");
    }
    parsedLoginDataSet.setExtractedString(sessionTokens.get("error"));
    if (parsedLoginDataSet.getExtractedString().equals("Success")) {
        GCMRegistrar.setRegisteredOnServer(mcontext, true);
        // Store the username and password in SharedPreferences after the
        // successful login
        SharedPreferences.Editor editor = mPreferences.edit();
        // editor.putString("UserName", email);
        // editor.putString("PassWord", password);
        editor.putString("AuthToken", sessionTokens.get("auth_token"));
        editor.commit();
        Message myMessage = new Message();
        myMessage.obj = "SUCCESS";
        handler.sendMessage(myMessage);
    } else {
        Log.e("my", "Login Error!");
    }
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

/**
 * Sends a JSON-string to the Google App Engine Server. This runs async in a separate thread.
 * /*from  w w  w  .j av a 2 s.  co  m*/
 * @param jsonString Content of HTTP request, as JSON.
 * @param targetHost The host of the server
 * @param httpPut The HTTP PUT request.
 */
private static void sendJSONTOGAEServer(final String jsonString, final HttpHost targetHost,
        final HttpPut httpPut) {
    Runnable sendRunnable = new Runnable() {

        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                StringEntity entity = new StringEntity(jsonString, "UTF-8");
                httpPut.setEntity(entity);

                // execute is a blocking call, it's best to call this code in a thread separate from the ui's
                HttpResponse response = httpClient.execute(targetHost, httpPut);

                Log.v("Put to GAE", response.getStatusLine().toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(null, sendRunnable, "putToGAE");
    thread.start();

}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/*from   w w w .  j a v  a  2s  . c o m*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ??URI???.//w ww.j a  v a  2  s. c o m
 * 
 * @param uri ????URI
 * @return 
 */
public static byte[] getBytes(final String uri) {
    HttpGet request = new HttpGet(uri);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        byte[] result = httpClient.execute(request, new ResponseHandler<byte[]>() {
            @Override
            public byte[] handleResponse(final HttpResponse response) throws IOException {
                switch (response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    return EntityUtils.toByteArray(response.getEntity());
                case HttpStatus.SC_NOT_FOUND:
                    throw new RuntimeException("No Found.");
                default:
                    throw new RuntimeException("Connection Error.");
                }
            }
        });
        return result;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.google.code.maven.plugin.http.client.utils.HttpRequestUtils.java

public static HttpResponse query(DefaultHttpClient httpclient, Request request, Proxy proxy, Log log)
        throws ClientProtocolException, IOException, MojoExecutionException {
    log.debug("preparing " + request);
    if (proxy != null) {
        log.info("setting up " + proxy + " for request " + request);
        proxy.prepare(httpclient);//from   www.j a  va 2s. c  o m
    }
    HttpRequestBase httpRequest = request.buildHttpRequestBase(httpclient, log);
    HttpHost targetHost = request.buildHttpHost(log);
    log.debug("HTTP " + request.getMethod() + " url=" + request.getFinalUrl());
    long responseTime = System.currentTimeMillis();
    HttpResponse response = httpclient.execute(targetHost, httpRequest);
    log.debug("received response (time=" + (System.currentTimeMillis() - responseTime) + "ms) for request ["
            + "HTTP " + request.getMethod() + " url=" + request.getFinalUrl() + "]");
    return response;
}

From source file:ca.sqlpower.wabit.enterprise.client.ServerInfoProvider.java

private static void init(String host, String port, String path, String username, String password)
        throws IOException {

    URL serverInfoUrl = toServerInfoURL(host, port, path);
    if (version.containsKey(generateServerKey(host, port, path, username, password)))
        return;/*from  w  ww  .  ja va 2 s .  c  o m*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(WabitClientSession.getCookieStore());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serverInfoUrl.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(serverInfoUrl.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(host, port, path, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(host, port, path, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(host, port, path, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, watermarkMessage, "SQL Power Wabit Server License",
                            JOptionPane.WARNING_MESSAGE);
                }
            });
        }

        // Now get the available fonts.
        URL serverFontsURL = toServerFontsURL(host, port, path);
        HttpUriRequest fontsRequest = new HttpGet(serverFontsURL.toURI());
        String fontsResponseBody = httpClient.execute(fontsRequest, new BasicResponseHandler());
        try {
            JSONArray fontsArray = new JSONArray(fontsResponseBody);
            List<String> fontNames = new ArrayList<String>();
            for (int i = 0; i < fontsArray.length(); i++) {
                fontNames.add(fontsArray.getString(i));
            }
            // Sort the list.
            Collections.sort(fontNames);
            fonts.put(generateServerKey(host, port, path, username, password), fontNames);
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:eu.thecoder4.gpl.pleftdroid.PleftBroker.java

/**
 * @return Returns SC_CLIREDIR if the client is being redirected (eg. for net authentication)
 *         or SC_NOTPLEFTSERV if the server is not Pleft Server
 *         or HttpStatus.SC_OK if everything is OK
 *///w  ww  .j a v  a 2  s . c  om
protected static int checkServer(String pserver) {
    DefaultHttpClient client = getDefaultClient();
    HttpContext context = new BasicHttpContext();
    //We request the index
    HttpGet request = new HttpGet(pserver);
    HttpResponse response = null;
    try {
        response = client.execute(request, context);
        int SC = response.getStatusLine().getStatusCode();
        Log.i("PB", "checkServ SC:" + SC);
    } catch (Exception e) {
        return SC_TIMEOUT;
    }
    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    String host = currentHost.getHostName();

    Log.i("PB", "checkServ finalhost=" + host + "==" + getHostName(pserver) + "=pserverhost ? "
            + host.equals(getHostName(pserver)));
    if (!host.equals(getHostName(pserver))) {
        try {
            response.getEntity().getContent().close(); //You need to open and close the IS to release the connection !!!
        } catch (Exception e) {
        }
        return SC_CLIREDIR;
    }
    //InputStream is;
    try {
        String html = EntityUtils.toString(response.getEntity()); //It consumes content !
        if (html.contains("Pleft")) {
            return HttpStatus.SC_OK;
        } else {
            Log.i("PB", "checkServ NOPLEFT!");
            return SC_NOTPLEFTSERV;
        }
    } catch (Exception e) {
        Log.i("PB", "checkServ Got exception2:" + e);
        return SC_NOTPLEFTSERV;
    }

}

From source file:com.amazon.advertising.api.sample.ItemLookupSample.java

private static void getItemInfo(String asin, SignedRequestsHelper helper) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Map<String, String> params = new HashMap<String, String>();
    params.put("Service", "AWSECommerceService");
    params.put("Version", "2011-08-01");
    params.put("Operation", "ItemLookup");
    params.put("ItemId", asin);
    params.put("ResponseGroup", "Images");
    String requestUrl = helper.sign(params);

    System.out.println("Request is \"" + requestUrl + "\"");
    HttpGet httpGet = new HttpGet(requestUrl);
    String responseBody = "";
    try {/*from  w w  w  .j av  a 2 s .  c o m*/
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = httpclient.execute(httpGet, responseHandler);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(responseBody);
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

@SuppressWarnings("unused")
private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request,
        ResponseHandler<T> handler) throws Exception {
    if (null == request) {
        throw new IllegalArgumentException("null request"); //$NON-NLS-1$
    }//  w  w w. jav  a  2 s.c  o m
    return client.execute(request, handler);
}