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:a.org.fakereplace.integration.jbossas.resteasy.changejaxbmodel.ChangeJaxbModelTestCase.java

private String performCall(String urlPattern) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse result = client.execute(new HttpGet(url + urlPattern));
    return HttpUtils.getContent(result);
}

From source file:com.brightcove.com.uploader.helper.WackyPageHelper.java

public String getDataForPage(Account pAccount, Environment pEnvironment, String pPage)
        throws MalformedURLException, HttpException, URISyntaxException, IOException {
    if (mToken == null) {
        createSession(pAccount, pEnvironment);
    }//from www.  ja v  a  2  s . c  o m
    URI signURI = new URL("http", pEnvironment.getServer("internal_jsps"), 18080, pPage).toURI();
    HttpGet httpGet = new HttpGet(signURI);
    HttpResponse response = null;
    DefaultHttpClient httpAgent = new DefaultHttpClient();
    response = httpAgent.execute(httpGet);

    HttpEntity entity = response.getEntity();
    String charSet = "UTF-8";

    String buffer = IOUtils.toString(entity.getContent(), charSet);

    return buffer;

}

From source file:fr.mixit.android.utils.NetworkUtils.java

static ResponseHttp getInputStreamFromDefaultHttpClient(String url, boolean isPost, String args) {
    final HttpParams httpParameters = new BasicHttpParams();

    // Set the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(httpParameters, BUFFER_SIZE);

    final DefaultHttpClient httpClient = getDefaultHttpClient(httpParameters);

    final ResponseHttp myResponse = new ResponseHttp();

    synchronized (httpClient) {
        if (cookieSession != null) {
            httpClient.getCookieStore().clear();
            httpClient.getCookieStore().addCookie(cookieSession);
        }/*from   ww w.j ava 2 s  .  c om*/

        try {
            HttpResponse response = null;

            if (isPost) {
                final HttpPost httpPost = new HttpPost(url);
                if (args != null) {
                    final StringEntity se = new StringEntity(args, HTTP.UTF_8);
                    httpPost.setEntity(se);
                }
                response = httpClient.execute(httpPost);
            } else {
                String urlWithParams = url;
                if (!isPost && args != null) {
                    urlWithParams = getGetURL(url, args);
                }
                final HttpGet httpGet = new HttpGet(urlWithParams);
                response = httpClient.execute(httpGet);
            }

            // Read data if entity is OK
            if (response != null) {
                myResponse.status = response.getStatusLine().getStatusCode();
                if (DEBUG_MODE) {
                    Log.d(TAG, "Status code : " + myResponse.status);
                }
                if (response.getEntity() != null) {
                    myResponse.jsonText = getJson(response.getEntity().getContent());
                }
            }

            cookieSession = getCookie(httpClient);

            // httpClient.getConnectionManager().shutdown();
        } catch (final UnsupportedEncodingException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "UTF8 unsupported", e);
            }
        } catch (final IllegalArgumentException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Invalid URL", e);
            }
        } catch (final ClientProtocolException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to get data", e);
            }
        } catch (final IllegalStateException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to read the data", e);
            }
        } catch (final IOException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to get or read the data", e);
            }
        }
    }

    return myResponse;
}

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

public static String driverPrefQuery(String name, String number, String nric, String license, int company,
        int type, String querytype) {
    HttpPost postJob = new HttpPost(HttpHelper.domain + "querydriver.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 a va2s. co m*/
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("name", name));
        infoJob.add(new BasicNameValuePair("number", number));
        infoJob.add(new BasicNameValuePair("nric", nric));
        infoJob.add(new BasicNameValuePair("license", license));
        infoJob.add(new BasicNameValuePair("company", Integer.toString(company)));
        infoJob.add(new BasicNameValuePair("type", Integer.toString(type)));
        infoJob.add(new BasicNameValuePair("querytype", querytype));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));
        HttpResponse response = clientJob.execute(postJob);

        String driver_id = HttpHelper.request(response);

        return driver_id;

    } catch (Exception ex) {
        return null;

    }

}

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

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }//from   w  w w  .ja v  a  2 s . c  om
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:a.org.fakereplace.integration.jbossas.clientproxy.jsf.ClientProxyEARJSFReplacementTest.java

@Test
public void testClientProxyReplacement() throws InterruptedException, NamingException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse result = client.execute(new HttpGet(url.toExternalForm() + "index.jsf"));
    String content = HttpUtils.getContent(result);
    Assert.assertTrue(content, content.contains("FIRST: a"));
    Assert.assertFalse(content, content.contains("SECOND: b"));
    final RemoteClassReplacer replacer = new RemoteClassReplacer();
    replacer.queueClassForReplacement(AppScopedBean.class, AppScopedBean1.class);
    replacer.queueResourceForReplacement(getClass(), "index.xhtml", "index1.xhtml");
    replacer.replaceQueuedClasses("test.war");
    result = client.execute(new HttpGet(url.toExternalForm() + "index.jsf"));
    content = HttpUtils.getContent(result);

    Assert.assertTrue(content, content.contains("FIRST: a"));
    Assert.assertTrue(content, content.contains("SECOND: b"));
}

From source file:com.jaeksoft.searchlib.test.legacy.CommonTestCase.java

@SuppressWarnings("deprecation")
public int postFile(File file, String contentType, String api) throws IllegalStateException, IOException {
    String url = SERVER_URL + "/" + api + "?use=" + INDEX_NAME + "&login=" + USER_NAME + "&key=" + API_KEY;
    HttpPut put = new HttpPut(url);
    put.setEntity(new FileEntity(file, contentType));
    DefaultHttpClient httpClient = new DefaultHttpClient();
    return httpClient.execute(put).getStatusLine().getStatusCode();
}

From source file:org.openml.knime.OpenMLWebservice.java

/**
 * Upload an implementation./* www  .j a  v a2 s.  co  m*/
 * 
 * 
 * @param description Implementation description file
 * @param workflow Workflow file
 * @param user Name of the user
 * @param password Password of the user
 * @return Response from the server
 * @throws Exception If communication failed
 */
public static String sendImplementation(final File description, final File workflow, final String user,
        final String password) throws Exception {
    String result = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80);
        httpclient.getCredentialsProvider().setCredentials(scope, credentials);
        String url = WEBSERVICEURL + "?f=openml.implementation.upload";
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity();
        FileBody descBin = new FileBody(description);
        reqEntity.addPart("description", descBin);
        FileBody workflowBin = new FileBody(workflow);
        reqEntity.addPart("source", workflowBin);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() < 200) {
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }
        if (resEntity != null) {
            result = convertStreamToString(resEntity.getContent());
        }
        ErrorDocument errorDoc = null;
        try {
            errorDoc = ErrorDocument.Factory.parse(result);
        } catch (Exception e) {
            // no error XML should mean no error
        }
        if (errorDoc != null && errorDoc.validate()) {
            ErrorDocument.Error error = errorDoc.getError();
            String errorMessage = error.getCode() + " : " + error.getMessage();
            if (error.isSetAdditionalInformation()) {
                errorMessage += " : " + error.getAdditionalInformation();
            }
            throw new Exception(errorMessage);
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
            // ignore
        }
    }
    return result;
}

From source file:com.googlecode.pondskum.client.LinkTraverserImpl.java

private HttpResponse openConnection(final DefaultHttpClient httpClient, final String url) throws IOException {
    HttpGet httpget = new HttpGet(url);
    return httpClient.execute(httpget);
}

From source file:org.jboss.as.testsuite.clustering.web.SimpleWebTestCase.java

@Test
public void test() throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {//from   www. jav a2 s.  c om
        HttpResponse response = client.execute(new HttpGet("http://localhost:8080/distributable/simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(Integer.parseInt(response.getFirstHeader("value").getValue()), 1);
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet("http://localhost:8080/distributable/simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(Integer.parseInt(response.getFirstHeader("value").getValue()), 2);
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}