List of usage examples for org.apache.commons.httpclient HttpClient HttpClient
public HttpClient()
From source file:com.predic8.membrane.core.interceptor.authentication.BasicAuthenticationInterceptorIntegrationTest.java
@Test public void testDeny() throws Exception { Rule rule = new ForwardingRule(new ForwardingRuleKey("localhost", "*", ".*", 8000), "thomas-bayer.com", 80); HttpRouter router = new HttpRouter(); router.getRuleManager().addRuleIfNew(rule); BasicAuthenticationInterceptor interceptor = new BasicAuthenticationInterceptor(); Map<String, String> mapping = new HashMap<String, String>(); mapping.put("admin", "admin"); interceptor.setUsers(mapping);//from www . ja va 2 s. c o m router.getTransport().getInterceptors().add(interceptor); HttpClient client = new HttpClient(); client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); int status = client.executeMethod(getGetMethod()); assertEquals(401, status); //TODO Basic Authentication test }
From source file:com.comcast.cats.service.util.HttpClientUtil.java
public static synchronized Object getForObject(String uri, Map<String, String> paramMap) { Object responseObject = new Object(); HttpMethod httpMethod = new GetMethod(uri); if ((null != paramMap) && (!paramMap.isEmpty())) { httpMethod.setQueryString(getNameValuePair(paramMap)); }// w w w .ja v a 2 s . c om Yaml yaml = new Yaml(); HttpClient client = new HttpClient(); InputStream responseStream = null; Reader inputStreamReader = null; try { int responseCode = client.executeMethod(httpMethod); if (HttpStatus.SC_OK != responseCode) { logger.error("[ REQUEST ] " + httpMethod.getURI().toString()); logger.error("[ METHOD ] " + httpMethod.getName()); logger.error("[ STATUS ] " + responseCode); } else { logger.trace("[ REQUEST ] " + httpMethod.getURI().toString()); logger.trace("[ METHOD ] " + httpMethod.getName()); logger.trace("[ STATUS ] " + responseCode); } responseStream = httpMethod.getResponseBodyAsStream(); inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF); responseObject = yaml.load(inputStreamReader); } catch (IOException ioException) { ioException.printStackTrace(); } finally { cleanUp(inputStreamReader, responseStream, httpMethod); } return responseObject; }
From source file:eu.eco2clouds.accounting.testbedclient.ClientHC.java
/** * Connects to an testbed URL to get the XML representations of Host Info * And it returns it as a null/*from ww w. j a v a 2s . c o m*/ * @param testbed object representing the testbed from which we want to know the host info * @return A XML string with the Host info, if there was any HTTP error, it returns empty String... */ public String getHostInfo(Testbed testbed) { // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod(testbed.getUrl()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); String response = ""; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... logger.warn("Get host information of testbed: " + testbed.getName() + " failed: " + method.getStatusLine()); } else { // Read the response body. byte[] responseBody = method.getResponseBody(); response = new String(responseBody); } } catch (HttpException e) { logger.warn("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.warn("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.antelink.sourcesquare.query.RestClient.java
protected RestTemplate getTemplate(String baseDomain) { HttpClient client = new HttpClient(); // Managing HTTP proxy - if any String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); if (proxyHost != null && proxyPort != null) { client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort)); }// w ww . j av a 2 s.c om // Managing HTTP proxy authentication - if any String proxyUser = System.getProperty("http.proxyUser"); String proxyPassword = System.getProperty("http.proxyPassword"); AuthScope auth; if (proxyHost != null && proxyUser != null && proxyPassword != null) { auth = new AuthScope(proxyHost, Integer.parseInt(proxyPort)); client.getState().setProxyCredentials(auth, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } else { auth = new AuthScope(baseDomain, AuthScope.ANY_PORT); client.getState().setCredentials(auth, null); } CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client) { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { ClientHttpRequest createRequest = super.createRequest(uri, httpMethod); createRequest.getHeaders().add("User-Agent", "SourceSquare"); return createRequest; } }; return new RestTemplate(commons); }
From source file:com.ifeng.vdn.ip.repository.service.impl.AliIPAddressChecker.java
@Override public IPAddress ipcheck(String ip) { AliIPBean ipaddress = null;/*from ww w .ja v a2 s. co m*/ String url = "http://ip.taobao.com/service/getIpInfo2.php"; // Create an instance of HttpClient. HttpClient clinet = new HttpClient(); // Create a method instance. PostMethod postMethod = new PostMethod(url); // Execute the method. // Read the response body. try { postMethod.setParameter("ip", ip); int resultCode = clinet.executeMethod(postMethod); if (resultCode == HttpStatus.SC_OK) { InputStream responseBody = postMethod.getResponseBodyAsStream(); ObjectMapper mapper = new ObjectMapper(); ipaddress = mapper.readValue(responseBody, AliIPBean.class); log.info(responseBody.toString()); } else { log.error("Method failedd: [{}] , IP: [{}]", postMethod.getStatusCode(), ip); } } catch (JsonParseException | JsonMappingException | HttpException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } return ipaddress; }
From source file:com.predic8.membrane.core.interceptor.InternalInvocationTest.java
private void callService(int port) throws HttpException, IOException { new HttpClient().executeMethod(new GetMethod("http://localhost:" + port)); }
From source file:com.esri.gpt.agp.client.AgpClient.java
/** Default constructor. */ public AgpClient() { super(); this.batchHttpClient = new HttpClient(); }
From source file:fr.msch.wissl.server.TestUsers.java
@Test public void test() throws IOException, JSONException { HttpClient client = new HttpClient(); // check the users and sessions created by TServer GetMethod get = new GetMethod(TServer.URL + "users"); get.addRequestHeader("sessionId", this.user_sessionId); client.executeMethod(get);/*from w w w .java 2 s. co m*/ Assert.assertEquals(200, get.getStatusCode()); JSONObject obj = new JSONObject(get.getResponseBodyAsString()); JSONArray users = obj.getJSONArray("users"); Assert.assertEquals(2, users.length()); for (int i = 0; i < 2; i++) { JSONObject u = users.getJSONObject(i); String username = u.getString("username"); if (username.equals(this.user_username)) { Assert.assertEquals(this.user_userId, u.getInt("id")); Assert.assertEquals(2, u.getInt("auth")); Assert.assertEquals(0, u.getInt("downloaded")); } else if (username.equals(this.admin_username)) { Assert.assertEquals(this.admin_userId, u.getInt("id")); Assert.assertEquals(1, u.getInt("auth")); Assert.assertEquals(0, u.getInt("downloaded")); } else { Assert.fail("Unexpected user:" + username); } } JSONArray sessions = obj.getJSONArray("sessions"); Assert.assertEquals(2, sessions.length()); for (int i = 0; i < 2; i++) { JSONObject s = sessions.getJSONObject(i); String username = s.getString("username"); if (username.equals(this.user_username)) { Assert.assertEquals(this.user_userId, s.getInt("user_id")); Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0 Assert.assertTrue(s.getInt("created_at") >= 0); Assert.assertFalse(s.has("origins")); // admin only Assert.assertFalse(s.has("last_played_song")); } } // unknown user: 404 get = new GetMethod(TServer.URL + "user/100"); get.addRequestHeader("sessionId", this.user_sessionId); client.executeMethod(get); Assert.assertEquals(404, get.getStatusCode()); // check admin user get = new GetMethod(TServer.URL + "user/" + this.admin_userId); get.addRequestHeader("sessionId", this.admin_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); JSONObject u = obj.getJSONObject("user"); Assert.assertEquals(this.admin_userId, u.getInt("id")); Assert.assertEquals(this.admin_username, u.getString("username")); Assert.assertEquals(1, u.getInt("auth")); Assert.assertEquals(0, u.getInt("downloaded")); sessions = obj.getJSONArray("sessions"); Assert.assertEquals(1, sessions.length()); JSONObject s = sessions.getJSONObject(0); Assert.assertEquals(this.admin_userId, s.getInt("user_id")); Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0 Assert.assertTrue(s.getInt("created_at") > 0); Assert.assertTrue(s.has("origins")); // admin only Assert.assertFalse(s.has("last_played_song")); Assert.assertTrue(obj.getJSONArray("playlists").length() == 0); // create a new user with user account: error 401 PostMethod post = new PostMethod(TServer.URL + "user/add"); post.addRequestHeader("sessionId", this.user_sessionId); post.addParameter("username", "new-user"); post.addParameter("password", "new-pw"); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // create new user with empty username: err 400 post = new PostMethod(TServer.URL + "user/add"); post.addRequestHeader("sessionId", this.admin_sessionId); post.addParameter("username", ""); post.addParameter("password", "new-pw"); post.addParameter("auth", "1"); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // create new user with short password: err 400 post = new PostMethod(TServer.URL + "user/add"); post.addRequestHeader("sessionId", this.admin_sessionId); post.addParameter("username", "new-user"); post.addParameter("password", "pw"); post.addParameter("auth", "1"); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // create new user with invalid auth: err 400 post = new PostMethod(TServer.URL + "user/add"); post.addRequestHeader("sessionId", this.admin_sessionId); post.addParameter("username", "new-user"); post.addParameter("password", "pw"); post.addParameter("auth", "3"); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); int new_userId = -1; String new_sessionId = null; String new_username = "new-user"; String new_password = "new-pw"; // create new user post = new PostMethod(TServer.URL + "user/add"); post.addRequestHeader("sessionId", this.admin_sessionId); post.addParameter("username", new_username); post.addParameter("password", new_password); post.addParameter("auth", "2"); client.executeMethod(post); Assert.assertEquals(200, post.getStatusCode()); u = new JSONObject(post.getResponseBodyAsString()).getJSONObject("user"); new_userId = u.getInt("id"); Assert.assertEquals(new_username, u.getString("username")); Assert.assertEquals(2, u.getInt("auth")); // check new user get = new GetMethod(TServer.URL + "user/" + new_userId); get.addRequestHeader("sessionId", this.user_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); Assert.assertTrue(obj.getJSONArray("playlists").length() == 0); Assert.assertEquals(0, obj.getJSONArray("sessions").length()); // login new user obj = new JSONObject(this.login(new_username, new_password)); Assert.assertEquals(new_userId, obj.getInt("userId")); new_sessionId = obj.getString("sessionId"); // check if logged in with /users get = new GetMethod(URL + "users"); get.addRequestHeader("sessionId", new_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); users = obj.getJSONArray("users"); Assert.assertEquals(3, users.length()); for (int i = 0; i < 3; i++) { u = users.getJSONObject(i); String username = u.getString("username"); if (username.equals(new_username)) { Assert.assertEquals(new_userId, u.getInt("id")); } else { Assert.assertTrue(username.equals(user_username) || username.equals(admin_username)); } } sessions = obj.getJSONArray("sessions"); Assert.assertEquals(3, sessions.length()); for (int i = 0; i < 3; i++) { s = sessions.getJSONObject(i); String username = s.getString("username"); if (username.equals(new_username)) { Assert.assertEquals(new_userId, s.getInt("user_id")); Assert.assertTrue(s.getInt("last_activity") >= 0); // might be 0 Assert.assertTrue(s.getInt("created_at") > 0); Assert.assertFalse(s.has("origins")); // admin only Assert.assertFalse(s.has("last_played_song")); } else { Assert.assertTrue(username.equals(user_username) || username.equals(admin_username)); } } // try to change password without the old password: 401 post = new PostMethod(URL + "user/password"); post.addRequestHeader("sessionId", new_sessionId); post.addParameter("old_password", "password"); post.addParameter("new_password", "password2"); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // change password for new user post = new PostMethod(URL + "user/password"); post.addRequestHeader("sessionId", new_sessionId); post.addParameter("old_password", new_password); new_password = "something else"; post.addParameter("new_password", new_password); client.executeMethod(post); Assert.assertEquals(204, post.getStatusCode()); // logout and relogin with new password post = new PostMethod(URL + "logout"); post.addRequestHeader("sessionId", new_sessionId); client.executeMethod(post); Assert.assertEquals(204, post.getStatusCode()); obj = new JSONObject(this.login(new_username, new_password)); Assert.assertEquals(new_userId, obj.getInt("userId")); new_sessionId = obj.getString("sessionId"); // try to delete an user as user: 401 post = new PostMethod(URL + "user/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("user_ids[]", "" + new_userId); client.executeMethod(post); Assert.assertEquals(401, post.getStatusCode()); // try to delete no user: 400 post = new PostMethod(URL + "user/remove"); post.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // try to delete admin with admin: 400 post = new PostMethod(URL + "user/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("user_ids[]", "" + admin_userId); client.executeMethod(post); Assert.assertEquals(400, post.getStatusCode()); // delete both regular users post = new PostMethod(URL + "user/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("user_ids[]", "" + user_userId); post.addParameter("user_ids[]", "" + new_userId); client.executeMethod(post); Assert.assertEquals(204, post.getStatusCode()); // check that old sessions do not work anymore get = new GetMethod(URL + "users"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); Assert.assertEquals(401, get.getStatusCode()); // check that there is only 1 user get = new GetMethod(URL + "users"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); Assert.assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); Assert.assertEquals(obj.getJSONArray("users").length(), 1); Assert.assertEquals(obj.getJSONArray("sessions").length(), 1); }
From source file:com.discursive.jccook.httpclient.ConditionalGetExample.java
public void start() throws HttpException, IOException { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://www.apache.org"); for (int i = 0; i < 3; i++) { setHeaders(method);// w w w. java 2 s.c om client.executeMethod(method); processResults(method); method.releaseConnection(); method.recycle(); } }
From source file:de.intranda.goobi.plugins.utils.SRUClient.java
/** * Queries the given catalog via Z.3950 (SRU) and returns its response. * /*from w w w. java2 s . c o m*/ * @param cat The catalog to query. * @param query The query. * @param recordSchema The expected record schema. * @return Query result XML string. */ public static String querySRU(ConfigOpacCatalogue cat, String query, String recordSchema) { String ret = null; if (query != null && !query.isEmpty()) { query = query.trim(); } if (cat != null) { String url = "http://"; url += cat.getAddress(); url += ":" + cat.getPort(); url += "/" + cat.getDatabase(); url += "?version=1.1"; url += "&operation=searchRetrieve"; url += "&query=" + query; url += "&maximumRecords=5"; url += "&recordSchema=" + recordSchema; logger.debug("SRU URL: " + url); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { client.executeMethod(method); ret = method.getResponseBodyAsString(); if (!method.getResponseCharSet().equalsIgnoreCase(ENCODING)) { // If response XML is not UTF-8, re-encode ret = convertStringEncoding(ret, method.getResponseCharSet(), ENCODING); } } catch (HttpException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { method.releaseConnection(); } } return ret; }