List of usage examples for org.apache.http.impl.client DefaultHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:com.fpmislata.clientejson.ClienteClienteTest.java
private static Cliente addCliente(String url, Cliente cliente) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("accept", "application/json; charset=UTF-8"); Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); String jsonString = gson.toJson(cliente); StringEntity input = new StringEntity(jsonString, "UTF-8"); input.setContentType("application/json"); httpPost.setEntity(input);/* www .j ava 2s . co m*/ HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } String personaResult = readObject(response); return gson.fromJson(personaResult, Cliente.class); }
From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java
public static void deleteRESTAppServerWithDB(String restServerName) { try {//from w ww. ja va 2 s. co m DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete( "http://localhost:8002/v1/rest-apis/" + restServerName + "?include=content&include=modules"); HttpResponse response = client.execute(delete); if (response.getStatusLine().getStatusCode() == 202) { Thread.sleep(3500); } } catch (Exception e) { // writing error to Log e.printStackTrace(); } }
From source file:de.hybris.platform.integration.cis.payment.strategies.impl.CisPaymentIntegrationTestHelper.java
public static Map<String, String> createNewProfile(final String cybersourceUrl, final List<BasicNameValuePair> formData) throws Exception // NO PMD { final DefaultHttpClient client = new DefaultHttpClient(); final HttpPost postRequest = new HttpPost(cybersourceUrl); postRequest.getParams().setBooleanParameter("http.protocol.handle-redirects", true); postRequest.setEntity(new UrlEncodedFormEntity(formData, "UTF-8")); // Execute HTTP Post Request final HttpResponse response = client.execute(postRequest); final Map<String, String> responseParams = new HashMap<String, String>(); BufferedReader bufferedReader = null; try {/*from w w w . j a v a 2 s .co m*/ bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while (bufferedReader.ready()) { final String currentLine = bufferedReader.readLine(); if (currentLine.contains("value=\"") && currentLine.contains("name=\"")) { final String[] splittedLine = currentLine.split("name=\""); final String key = splittedLine[1].split("value=\"")[0].replace("\"", "").replace(">", "") .trim(); final String value = splittedLine[1].split("value=\"")[1].replace("\"", "").replace(">", "") .trim(); responseParams.put(key, value); } } } finally { IOUtils.closeQuietly(bufferedReader); } return responseParams; }
From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java
public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {// w ww . ja v a 2 s .c om HttpGet httpget = new HttpGet(URL); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); // We should get the Login Page StatusLine statusLine = response.getStatusLine(); System.out.println("Login form get: " + statusLine); assertEquals(200, statusLine.getStatusCode()); System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // We should now login with the user name and password HttpPost httpost = new HttpPost(URL + "/j_security_check"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("j_username", user)); nvps.add(new BasicNameValuePair("j_password", pass)); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); statusLine = response.getStatusLine(); // Post authentication - we have a 302 assertEquals(302, statusLine.getStatusCode()); Header locationHeader = response.getFirstHeader("Location"); String location = locationHeader.getValue(); HttpGet httpGet = new HttpGet(location); response = httpclient.execute(httpGet); entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // Either the authentication passed or failed based on the expected status code statusLine = response.getStatusLine(); assertEquals(expectedStatusCode, statusLine.getStatusCode()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.ginstr.android.service.opencellid.library.data.ApiKeyHandler.java
/** * Query server to generate a new random API key. * Use this if you don't want to register at opencellid.org to * get a random key to upload/download data. * This function will store the retrieved key to a file. * /*from w w w . j a va2s. com*/ * @return valid API key or null if call failed */ private static String requestNewKey(boolean testMode) { // get a key from server and store it on the SD card String responseFromServer = null; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(OpenCellIdLibContext.getServerURL(testMode) + KEY_GENERATOR_URL_DEFAULT); Log.d(ApiKeyHandler.class.getSimpleName(), "Connecting to " + KEY_GENERATOR_URL_DEFAULT + " for a new API key..."); HttpResponse result = httpclient.execute(httpGet); StatusLine status = result.getStatusLine(); if (status.getStatusCode() == 200) { if (result.getEntity() != null) { InputStream is = result.getEntity().getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[4096]; while ((readBytes = is.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } responseFromServer = content.toString(); result.getEntity().consumeContent(); } Log.d(ApiKeyHandler.class.getSimpleName(), "New API key set => " + responseFromServer); //store new key into defined file writeApiKeyToFile(responseFromServer, testMode); return responseFromServer; } else { Log.d(ApiKeyHandler.class.getSimpleName(), "Returned " + status.getStatusCode() + " " + status.getReasonPhrase()); } httpclient = null; httpGet = null; result = null; } catch (Exception e) { Log.e(ApiKeyHandler.class.getSimpleName(), "", e); } return null; }
From source file:com.meltmedia.cadmium.blackbox.test.CadmiumAssertions.java
/** * <p>Asserts that a remote resource exists.</p> * @param message The message that will be in the error if the remote resource doesn't exist. * @param remoteLocation A string containing the URL location of the remote resource to check. * @param username The Basic HTTP auth username. * @param password The Basic HTTP auth password. * @return The content of the remote file. *//* w ww . j a v a 2s . c om*/ public static HttpEntity assertExistsRemotely(String message, String remoteLocation, String username, String password) { DefaultHttpClient client = new DefaultHttpClient(); try { HttpGet get = new HttpGet(remoteLocation); if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) { get.setHeader("Authorization", encodeForBasicAuth(username, password)); } HttpResponse resp = client.execute(get); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new AssertionFailedError(message); } return resp.getEntity(); } catch (ClientProtocolException e) { throw new AssertionFailedError(e.getMessage() + ": " + message); } catch (IOException e) { throw new AssertionFailedError(e.getMessage() + ": " + message); } }
From source file:com.github.koraktor.steamcondenser.steam.community.WebApi.java
/** * Fetches data from Steam Web API using the specified interface, method * and version. Additional parameters are supplied via HTTP GET. Data is * returned as a String in the given format. * * @param apiInterface The Web API interface to call, e.g. * <code>ISteamUser</code> * @param format The format to load from the API ("json", "vdf", or "xml") * @param method The Web API method to call, e.g. * <code>GetPlayerSummaries</code> * @param params Additional parameters to supply via HTTP GET * @param version The API method version to use * @return Data is returned as a String in the given format (which may be * "json", "vdf", or "xml")./*from w ww.java2s.c o m*/ * @throws WebApiException In case of any request failure */ public static String load(String format, String apiInterface, String method, int version, Map<String, Object> params) throws WebApiException { String protocol = secure ? "https" : "http"; String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method, version); if (params == null) { params = new HashMap<String, Object>(); } params.put("format", format); if (apiKey != null) { params.put("key", apiKey); } boolean first = true; for (Map.Entry<String, Object> param : params.entrySet()) { if (first) { first = false; } else { url += '&'; } url += String.format("%s=%s", param.getKey(), param.getValue()); } if (LOG.isLoggable(Level.INFO)) { String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET"); LOG.info("Querying Steam Web API: " + debugUrl); } String data; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Integer statusCode = response.getStatusLine().getStatusCode(); if (!statusCode.toString().startsWith("20")) { if (statusCode == 401) { throw new WebApiException(WebApiException.Cause.UNAUTHORIZED); } throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode, response.getStatusLine().getReasonPhrase()); } data = EntityUtils.toString(response.getEntity()); } catch (WebApiException e) { throw e; } catch (Exception e) { throw new WebApiException("Could not communicate with the Web API.", e); } return data; }
From source file:com.github.koraktor.steamcondenser.community.WebApi.java
/** * Fetches data from Steam Web API using the specified interface, method * and version. Additional parameters are supplied via HTTP GET. Data is * returned as a String in the given format. * * @param apiInterface The Web API interface to call, e.g. * <code>ISteamUser</code> * @param format The format to load from the API ("json", "vdf", or "xml") * @param method The Web API method to call, e.g. * <code>GetPlayerSummaries</code> * @param params Additional parameters to supply via HTTP GET * @param version The API method version to use * @return Data is returned as a String in the given format (which may be * "json", "vdf", or "xml").// ww w . java2 s. c o m * @throws WebApiException In case of any request failure */ public static String load(String format, String apiInterface, String method, int version, Map<String, Object> params) throws WebApiException { String protocol = secure ? "https" : "http"; String url = String.format("%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method, version); if (params == null) { params = new HashMap<String, Object>(); } params.put("format", format); if (apiKey != null) { params.put("key", apiKey); } boolean first = true; for (Map.Entry<String, Object> param : params.entrySet()) { if (first) { first = false; } else { url += '&'; } url += String.format("%s=%s", param.getKey(), param.getValue()); } if (LOG.isInfoEnabled()) { String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET"); LOG.info("Querying Steam Web API: " + debugUrl); } String data; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Integer statusCode = response.getStatusLine().getStatusCode(); if (!statusCode.toString().startsWith("20")) { if (statusCode == 401) { throw new WebApiException(WebApiException.Cause.UNAUTHORIZED); } throw new WebApiException(WebApiException.Cause.HTTP_ERROR, statusCode, response.getStatusLine().getReasonPhrase()); } data = EntityUtils.toString(response.getEntity()); } catch (WebApiException e) { throw e; } catch (Exception e) { throw new WebApiException("Could not communicate with the Web API.", e); } return data; }
From source file:costumetrade.common.util.HttpClientUtils.java
public static String get(String url, String encoding) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); try {// w w w . j a va 2 s. c o m httpclient.getParams().setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); //log.info("GET "+url); HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"); HttpResponse response = httpclient.execute(httpget); //log.info(response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, encoding); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } }
From source file:dk.moerks.ratebeermobile.io.NetBroker.java
public static String doGet(Context context, DefaultHttpClient httpclient, String url) throws NetworkException { if (httpclient == null) { httpclient = init();/*w ww .j a va2s. c om*/ } Log.d(LOGTAG, "URL: " + url); HttpGet httpget = new HttpGet(url); try { // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpget); String result = responseString(response); response.getEntity().consumeContent(); return result; } catch (ClientProtocolException e) { } catch (IOException e) { } catch (Exception e) { throw new NetworkException(context, LOGTAG, "Network Error - Do you have a network connection?", e); } return null; }