String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, value);
LOG.trace("enter HttpMethodBase.readStatusLine(HttpState, HttpConnection)"); final int maxGarbageLines = getParams(). getIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE); String s; do { s = conn.readLine(getParams().getHttpElementCharset()); if (s == null && count == 0) { throw new NoHttpResponseException("The server " + conn.getHost() + " failed to respond"); } else if (s == null || count >= maxGarbageLines) { throw new ProtocolException("The server " + conn.getHost() + " failed to respond with a valid HTTP response"); if (getParams().isParameterFalse(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE) && versionStr.equals("HTTP")) { getParams().setVersion(HttpVersion.HTTP_1_0); if (LOG.isWarnEnabled()) { LOG.warn("Ambiguous status line (HTTP protocol version missing):" +
throw new IllegalStateException("Oauth2 token is not set!"); headers.add(new Header("Authorization", "OAuth2 " + token)); headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress())); client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); for (Header hd : headers) { log(hd.getName() + ": " + hd.getValue()); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); client.executeMethod(method); Header[] resHeader = method.getResponseHeaders(); responseCode = method.getStatusCode(); log("Response:"); log("https StatusCode:" + String.valueOf(responseCode));
HttpClient client = new HttpClient(); param.setContentCharset("UTF-8"); client.executeMethod(getMethod); String res = getMethod.getResponseBodyAsString(); if(res.startsWith("http://") || res.startsWith("https://")){
try { method = new GetMethod(testUrl); method.getParams().setParameter("http.socket.timeout", DEFAULT_CONNECT_TIMEOUT_MILLIS > 0 ? DEFAULT_CONNECT_TIMEOUT_MILLIS : new Integer(30 * 1000)); HttpClient client = new HttpClient(); if (Util.fixEmptyAndTrim(name) != null && !isNoProxyHost(host, noProxyHost)) { client.getHostConfiguration().setProxy(name, port); Credentials credentials = createCredentials(userName, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, credentials);
public String doPost(String url, String charset, String jsonObj) { String resStr = null; HttpClient htpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, charset); try { postMethod.setRequestEntity(new StringRequestEntity(jsonObj, "application/json", charset)); int statusCode = htpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { String location = null; if (locationHeader != null) { location = locationHeader.getValue(); log.info("The page was redirected to :" + location); } else {
@Ignore @Test public void testRestAPI() throws IOException { HttpClient client = new HttpClient(); // To be avoided unless in debug mode Credentials defaultcreds = new UsernamePasswordCredentials("admin", "111111"); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, defaultcreds); PutMethod method = new PutMethod("http://localhost:8080/agent/api/36"); final HttpMethodParams params = new HttpMethodParams(); params.setParameter("action", "approve"); method.setParams(params); final int i = client.executeMethod(method); System.out.println(method.getResponseBodyAsString()); } }
private List<Evidence> search(String query) { List<Evidence> evidences = new ArrayList<>(); try { HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(query); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + getMethod.getStatusLine());
/** * GET urls in parallel using the executor service. * @param urls absolute URLs to GET * @param timeoutMs timeout in milliseconds for each GET request * @return instance of CompletionService. Completion service will provide * results as they arrive. The order is NOT same as the order of URLs */ public CompletionService<GetMethod> execute(List<String> urls, int timeoutMs) { HttpClientParams clientParams = new HttpClientParams(); clientParams.setConnectionManagerTimeout(timeoutMs); HttpClient client = new HttpClient(clientParams, _connectionManager); CompletionService<GetMethod> completionService = new ExecutorCompletionService<>(_executor); for (String url : urls) { completionService.submit(() -> { try { GetMethod getMethod = new GetMethod(url); getMethod.getParams().setSoTimeout(timeoutMs); client.executeMethod(getMethod); return getMethod; } catch (Exception e) { // Log only exception type and message instead of the whole stack trace LOGGER.warn("Caught '{}' while executing GET on URL: {}", e.toString(), url); throw e; } }); } return completionService; } }
method.getParams().setSoTimeout(timeout); int responseCode = httpClient.executeMethod(method); Object body = HttpHelper.readResponseBodyFromInputStream(method.getResponseBodyAsStream(), exchange); Header[] headers = method.getResponseHeaders(); HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy(); for (Header header : headers) { String name = header.getName(); String value = header.getValue(); if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) { message.setHeader(name, value);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(expireSeconds > 0 ? expireSeconds * 1000 : 5000); if (logger.isDebugEnabled()) logger.debug("http Request QueryString: " + postMethod.getQueryString()); BufferedReader bufferedreader = null; try { int status = httpClient.executeMethod(postMethod); in = postMethod.getResponseBodyAsStream(); if (charSet == null) charSet = postMethod.getResponseCharSet(); String location = null; if(locationHeader != null){ location = locationHeader.getValue(); return getHttpRequest("",location,3);
method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); method.getParams().setSoTimeout(client.getParams().getSoTimeout()); adjustHttpHeader(method); client.executeMethod(method);
public int get(String url) throws HttpException, IOException { final GetMethod get = new GetMethod(url); get.getParams().setContentCharset("UTF-8"); return httpClient.executeMethod(get); }
if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try httpClient.executeMethod(post); if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) if (locationHeader != null) String redirectLocation = locationHeader.getValue(); post.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(post);
private boolean acquireServerAddresses() { HostAndPort hostAndPort = readNameServerAddresses(); httpClient.getHostConfiguration().setHost(hostAndPort.getHost(), hostAndPort.getPort()); HttpMethod httpMethod = new GetMethod(Constants.DIAMOND_HTTP_URI); HttpMethodParams params = new HttpMethodParams(); params.setSoTimeout(diamondManagerConf.getOnceTimeout()); httpMethod.setParams(params); try { if (Constants.SC_OK != httpClient.executeMethod(httpMethod)) { log.warn("no diamond servers available from {}.", httpClient.getHostConfiguration().getHost()); return false; } List<String> newDomainNameList = IOUtils.readLines(httpMethod.getResponseBodyAsStream()); if (newDomainNameList.size() > 0) { HashSet<String> diamondServers = Sets.newHashSet(newDomainNameList); log.info("got diamond servers {} from NameServer {}", diamondServers, httpClient.getHostConfiguration().getHost()); diamondManagerConf.setDiamondServers(diamondServers, diamondHttpClient); saveServerAddressesToLocal(); return true; } } catch (Exception e) { log.error("failed to get diamond servers from {} with error {}", httpClient.getHostConfiguration().getHost(), Throwables.getStackTraceAsString(e)); } finally { httpMethod.releaseConnection(); } return false; }
method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); int responseStatus = http.executeMethod(method);
private enum ExecuteResult { SUCCESS, RETRY };
m.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); m.addParameter("credentials[username]", getUserName()); m.addParameter("credentials[password]", getPassword()); try { client.executeMethod(m); if (m.getStatusCode() != HttpStatus.SC_OK && m.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { throw new InvalidParameterException("Invalid PT credentials. HTTP reply code " + m.getStatusCode()); String value = cookies[i].getValue(); if (i == 0) authCookie += value.split(";")[0]; String location = l.getValue(); GetMethod gm = new GetMethod(location); gm.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); gm.setRequestHeader("Cookie", authCookie); client.executeMethod(gm); if (gm.getStatusCode() != HttpStatus.SC_OK && gm.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { throw new InvalidParameterException("Invalid PT credentials. HTTP reply code " + m.getStatusCode());
getMethod.getParams().setContentCharset(null); // to avoid wrong Charsets! getMethod.setQueryString("SERVICE=" + service + "&REQUEST=GetCapabilities"); client.executeMethod(getMethod); InputStream in = getMethod.getResponseBodyAsStream(); String contentType = (contentTypeHeader != null) ? contentTypeHeader.getValue() : "";