List of usage examples for org.apache.commons.httpclient HttpMethod getURI
public abstract URI getURI() throws URIException;
From source file:com.gisgraphy.rest.RestClient.java
private int executeAndCheckStatusCode(HttpMethod httpMethod) throws IOException, HttpException, RestClientException { int statusCode = httpClient.executeMethod(httpMethod); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) { throw new RestClientException(statusCode, "restclient exception for " + httpMethod.getURI() + " : " + statusCode + ", " + HttpStatus.getStatusText(statusCode)); }/* w w w. ja va 2s . co m*/ return statusCode; }
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
private void sendRequest(BaseRequest request, @Nonnull HttpMethod method, String requestBody) { String uri = null;/*from w w w .j a v a 2 s . c om*/ long waitTime = 0L; try { uri = method.getURI().toString(); logger.debug(request.getLogUtil().getLogMessage( "About to " + method.getName() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); List<String> cookies = new ArrayList<String>(); if (httpclient != null && httpclient.getState() != null && httpclient.getState().getCookies() != null) { for (Cookie cookie : httpclient.getState().getCookies()) { cookies.add("REQUEST COOKIE: " + cookie.toExternalForm() + " (domain=" + cookie.getDomain() + " : path=" + cookie.getPath() + ")"); } } request.logRequest(uri, requestBody, method.getName(), request.getHeaderInformation(), cookies, false); setHeaders(request, method, request.getHeaderInformation()); long startTime = System.currentTimeMillis(); request.setTimestamp(new Date(startTime)); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); processResponse(responseBody, startTime, endTime, request, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(request.getLogUtil().getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { try { method.releaseConnection(); } catch (Exception e) { logger.warn("Could not release connection: " + e, e); } if (method.getName().equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { logger.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java
private HttpMethod createNewHttpMethod(HttpMethod oldMethod) throws URIException { HttpMethod httpMethod;/* www .j av a 2 s. com*/ if (oldMethod instanceof GetMethod) { httpMethod = new GetMethod(); } else { httpMethod = new PostMethod(); ((PostMethod) httpMethod).setRequestEntity(((PostMethod) oldMethod).getRequestEntity()); httpMethod.setParams(oldMethod.getParams()); } httpMethod.setURI(oldMethod.getURI()); httpMethod.setFollowRedirects(oldMethod.getFollowRedirects()); return httpMethod; }
From source file:net.oauth.client.OAuthHttpClient.java
/** Send a message to the service provider and get the response. */ @Override//from w w w . j a v a2 s. c om protected OAuthMessage invoke(OAuthMessage message) throws Exception { String form = OAuth.formEncode(message.getParameters()); HttpMethod method; if ("GET".equals(message.httpMethod)) { method = new GetMethod(message.URL); method.setQueryString(form); // method.addRequestHeader("Authorization", message // .getAuthorizationHeader(serviceProvider.userAuthorizationURL)); method.setFollowRedirects(false); } else { PostMethod post = new PostMethod(message.URL); post.setRequestEntity(new StringRequestEntity(form, OAuth.FORM_ENCODED, null)); method = post; } clientPool.getHttpClient(new URL(method.getURI().toString())).executeMethod(method); final OAuthMessage response = new HttpMethodResponse(method); int statusCode = method.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Map<String, Object> dump = response.getDump(); OAuthProblemException problem = new OAuthProblemException( (String) dump.get(OAuthProblemException.OAUTH_PROBLEM)); problem.getParameters().putAll(dump); throw problem; } return response; }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a GET Message./*from w w w .j av a 2s . c o m*/ * * @param authgets * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws CookieException on problems * @throws ProcessException on problems */ public byte[] get(HttpMethod authgets) throws IOException, CookieException, ProcessException { showCookies(client); byte[] out = null; authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); // System.err.println(authgets.getParams().getParameter("http.protocol.content-charset")); client.executeMethod(authgets); LOG.debug(authgets.getURI()); LOG.debug("GET: " + authgets.getStatusLine().toString()); out = authgets.getResponseBody(); // release any connection resources used by the method authgets.releaseConnection(); int statuscode = authgets.getStatusCode(); if (statuscode == HttpStatus.SC_NOT_FOUND) { LOG.warn("Not Found: " + authgets.getQueryString()); throw new FileNotFoundException(authgets.getQueryString()); } return out; }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private String getFileNameFromURL(HttpMethod method) { String filename = ""; try {/*from w w w .ja v a2 s . com*/ String baseName = FilenameUtils.getBaseName(method.getURI().getURI()); String extension = FilenameUtils.getExtension(method.getURI().getURI()); extension = extension.substring(0, extension.indexOf("&") < 0 ? extension.length() : extension.indexOf("&")); extension = extension.substring(0, extension.indexOf("?") < 0 ? extension.length() : extension.indexOf("?")); if (StringUtils.isNotEmpty(baseName) && StringUtils.isNotEmpty(extension)) { filename = baseName + "." + extension; } } catch (URIException e) { LOG.warn("cant parse url for getting filename", e); } return filename; }
From source file:com.mobilefirst.fiberlink.WebServiceRequest.java
/** * Description: Send Request method//from w w w . j a v a2s.c o m * @param method: the type of HTTP Method to send * @param responseToVerify: string to verify in the response * @return whether the response was verified * @throws Exception */ private boolean sendRequest(HttpMethod method, String responseToVerify) throws Exception { boolean isResponseVerified = false; try { statusCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString(); System.out.println("Request URL :: " + method.getURI()); System.out.println( "------------------------------------Begin Debug: Request Headers----------------------------------------------------------\n"); Header[] requestHeaders = method.getRequestHeaders(); for (int cn = 0; cn < requestHeaders.length; cn++) { System.out.println(requestHeaders[cn].toString()); } System.out.println( "------------------------------------Begin Debug: Response Headers----------------------------------------------------------\n"); Header[] responseHeaders = method.getResponseHeaders(); for (int cn = 0; cn < responseHeaders.length; cn++) { System.out.println(responseHeaders[cn].toString()); } System.out.println( "------------------------------------End Debug----------------------------------------------------------\n"); if (statusCode != HttpStatus.SC_OK) { throw new Exception("POST method failed :: " + statusCode + " and ResponseBody :: " + responseBody); } else { System.out.println( "------------------------------------Response Start----------------------------------------------------------\n"); System.out.println(responseBody + "\n"); System.out.println( "------------------------------------Resoonse End----------------------------------------------------------"); if (null == jsessionId) { for (int cnt = 0; cnt < responseHeaders.length; cnt++) { // System.out.println(headers[cnt].toString()); if (responseHeaders[cnt].toString().contains("Set-Cookie: JSESSIONID=")) { jsessionId = getPatternMatches("JSESSIONID=(.+); Path", responseHeaders[cnt].toString(), false); System.out.println("JESSIONID: " + jsessionId); break; } } } if (responseBody.toLowerCase().contains(responseToVerify.toLowerCase())) { System.out.println("RESPONSE VERIFIED. Contains: " + responseToVerify); isResponseVerified = true; } } } catch (Exception e) { e.printStackTrace(); throw new Exception("Exception in sendRequest method..." + e.getMessage()); } return isResponseVerified; }
From source file:com.intuit.tank.http.BaseRequest.java
public void sendRequest(BaseResponse response, @Nonnull HttpMethod method, String requestBody) { String uri = null;//w w w .ja va 2 s.com long waitTime = 0L; try { this.response = response; uri = method.getURI().toString(); logger.debug( LogUtil.getLogMessage("About to POST request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); logRequest(uri, requestBody, method.getName(), headerInformation, httpclient, false); BaseRequestHandler.setHeaders(method, headerInformation); long startTime = System.currentTimeMillis(); timestamp = new Date(startTime); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); BaseRequestHandler.processResponse(responseBody, startTime, endTime, response, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(LogUtil.getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { method.releaseConnection(); } if (waitTime != 0) { doWaitDueToLongResponse(waitTime, uri); } }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private void signWithOAuth(HttpMethod method) throws IOException { try {//from w w w .j ava2 s . co m HostConfiguration hostConfiguration = client.getHostConfiguration(); URI uri = method.getURI(); URI newUri = new URI((isSSLEnabled) ? "https" : "http", uri.getUserinfo(), hostConfiguration.getHost(), hostConfiguration.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); method.setURI(newUri); //URI checkUri = method.getURI(); //String checkUriString = checkUri.toString(); CommonsHttp3OAuthConsumer oAuthConsumer = new CommonsHttp3OAuthConsumer(consumerKey, consumerSecret); oAuthConsumer.setTokenWithSecret(consumerKey, consumerSecret); oAuthConsumer.sign(method); } catch (Exception e) { throw new IOException("Failed to OAuth sign HTTPRequest", e); } }
From source file:com.cyberway.issue.crawler.datamodel.credential.HtmlFormCredential.java
public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method, String payload) { // http is not used. // payload is not used. boolean result = false; Map formItems = null;/*from ww w . j a va 2 s .c o m*/ try { formItems = getFormItems(curi); } catch (AttributeNotFoundException e1) { logger.severe("Failed get of form items for " + curi); } if (formItems == null || formItems.size() <= 0) { try { logger.severe("No form items for " + method.getURI()); } catch (URIException e) { logger.severe("No form items and exception getting uri: " + e.getMessage()); } return result; } NameValuePair[] data = new NameValuePair[formItems.size()]; int index = 0; String key = null; for (Iterator i = formItems.keySet().iterator(); i.hasNext();) { key = (String) i.next(); data[index++] = new NameValuePair(key, (String) formItems.get(key)); } if (method instanceof PostMethod) { ((PostMethod) method).setRequestBody(data); result = true; } else if (method instanceof GetMethod) { // Append these values to the query string. // Get current query string, then add data, then get it again // only this time its our data only... then append. HttpMethodBase hmb = (HttpMethodBase) method; String currentQuery = hmb.getQueryString(); hmb.setQueryString(data); String newQuery = hmb.getQueryString(); hmb.setQueryString(((StringUtils.isNotEmpty(currentQuery)) ? currentQuery + "&" : "") + newQuery); result = true; } else { logger.severe("Unknown method type: " + method); } return result; }