List of usage examples for org.apache.commons.httpclient HttpMethod getURI
public abstract URI getURI() throws URIException;
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a GET Message.// w w w .jav a2s . c om * * @param authgets * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws CookieException on problems * @throws ProcessException on problems */ protected String get(HttpMethod authgets, ContentProcessable cp) throws IOException, CookieException, ProcessException { showCookies(client); String out = ""; authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); // System.err.println(authgets.getParams().getParameter("http.protocol.content-charset")); client.executeMethod(authgets); cp.validateReturningCookies(client.getState().getCookies(), authgets); LOG.debug(authgets.getURI()); LOG.debug("GET: " + authgets.getStatusLine().toString()); out = authgets.getResponseBodyAsString(); out = cp.processReturningText(out, authgets); // 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.authHelper.customescheme.negotiate.CustomNegotiateScheme.java
/** * Produces Negotiate authorization string based on token created by * processChallenge./*from w ww . jav a 2 s. c o m*/ * * @param credentials Never used be the Negotiate scheme but must be provided to * satisfy common-httpclient API. Credentials from JAAS will be used insted. * @param method The method being authenticated * * @throws org.apache.commons.httpclient.auth.AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an Negotiate authorization string * * @since 3.0 */ public synchronized String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { LOG.info("enter CustomNegotiateScheme.authenticate(Credentials, HttpMethod)"); if (state == UNINITIATED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { try { if (context == null) { LOG.info("host: " + method.getURI().getHost()); init(method.getURI().getHost(), (UsernamePasswordCredentials) credentials); } } catch (org.apache.commons.httpclient.URIException urie) { LOG.severe(urie.getMessage()); state = FAILED; throw new AuthenticationException(urie.getMessage()); } // HTTP 1.1 issue: // Mutual auth will never complete do to 200 insted of 401 in // return from server. "state" will never reach ESTABLISHED // but it works anyway // token = context.initSecContext(token, 0, token.length); LOG.info("got token, sending " + token.length + " to server"); } catch (GSSException gsse) { LOG.severe(gsse.getMessage()); state = FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) { throw new InvalidCredentialsException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.NO_CRED) { throw new CredentialsNotAvailableException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) { throw new AuthChallengeException(gsse.getMessage(), gsse); } // other error throw new AuthenticationException(gsse.getMessage()); } return "Negotiate " + new String(new Base64(-1).encode(token)); }
From source file:edu.caltech.ipac.firefly.server.network.HttpServices.java
/** * Execute the given HTTP method with the given parameters. * @param method the function or method to perform * @param cookies optional, sent with request if present. * @return true is the request was successfully received, understood, and accepted (code 2xx). */// w w w.java2s . c o m public static boolean executeMethod(HttpMethod method, String userId, String password, Map<String, String> cookies) { try { if (!StringUtils.isEmpty(userId)) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } else { // check to see if the userId and password is in the url userId = URLDownload.getUserFromUrl(method.toString()); if (userId != null) { password = URLDownload.getPasswordFromUrl(method.toString()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } } if (cookies != null) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : cookies.entrySet()) { if (sb.length() > 0) sb.append("; "); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } if (sb.length() > 0) { method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); method.setRequestHeader("Cookie", sb.toString()); } } int status = httpClient.executeMethod(method); boolean isSuccess = status >= 200 && status < 300; String reqDesc = "URL:" + method.getURI(); if (isSuccess) { LOG.info(reqDesc); } else { reqDesc = reqDesc + "\nREQUEST HEADERS: " + CollectionUtil.toString(method.getRequestHeaders()).replaceAll("\\r|\\n", "") + "\nPARAMETERS:\n " + getDesc(method.getParams()) + "\nRESPONSE HEADERS: " + CollectionUtil.toString(method.getResponseHeaders()).replaceAll("\\r|\\n", ""); LOG.error("HTTP request failed with status:" + status + "\n" + reqDesc); } return isSuccess; } catch (Exception e) { LOG.error(e, "Unable to connect to:" + method.toString()); } return false; }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *//*from w w w . j ava2 s . c om*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest) throws IOException, RedirectRequiredException { //Utils.traceRequest(httpServletRequest); // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); _log.debug("Sending request to " + httpMethodProxyRequest.getURI()); for (Header header : httpMethodProxyRequest.getRequestHeaders()) { _log.debug(" Header \"" + header.getName() + "\" = \"" + header.getValue() + "\""); } // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Persist the respose headers this.responseHeaderMap = new HashMap<String, List<String>>(); for (Header header : this.httpMethod.getResponseHeaders()) { responseHeaderMap.put(header.getName(), Arrays.asList(header.getValue())); } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(HttpConstants.STRING_LOCATION_HEADER) .getValue(); if (stringLocation == null) { throw new IOException("Recieved status code: " + stringStatusCode + " but no " + HttpConstants.STRING_LOCATION_HEADER + " header was found in the response"); } throw new RedirectRequiredException(new URL(stringLocation)); } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. //httpServletResponse.setIntHeader(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME, 0); //httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } // Pass the response code back to the client this.httpStatusCode = intProxyResponseCode; _log.debug("Response code was " + this.httpStatusCode); // Pass response headers back to the client // TODO: Implement support for proxying response headers //Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); //for(Header header : headerArrayResponse) { // httpServletResponse.setHeader(header.getName(), header.getValue()); //} // Send the content to the client //InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); //BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); //OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); //int intNextByte; //while ( ( intNextByte = bufferedInputStream.read() ) != -1 ) { // outputStreamClientResponse.write(intNextByte); //} }
From source file:com.hp.alm.ali.rest.client.AliRestClient.java
private void writeResponse(ResultInfo result, HttpMethod method, boolean writeBodyAndHeaders) { OutputStream bodyStream = result.getBodyStream(); StatusLine statusLine = method.getStatusLine(); if (statusLine != null) { result.setReasonPhrase(statusLine.getReasonPhrase()); }/* www .j a v a 2 s. co m*/ try { result.setLocation(method.getURI().toString()); } catch (URIException e) { throw new RuntimeException(e); } if (writeBodyAndHeaders) { Map<String, String> headersMap = result.getHeaders(); Header[] headers = method.getResponseHeaders(); for (Header header : headers) { headersMap.put(header.getName(), header.getValue()); } } result.setHttpStatus(method.getStatusCode()); Filter filter = new IdentityFilter(result); for (ResponseFilter responseFilter : responseFilters) { filter = responseFilter.applyFilter(filter, method, result); } if (writeBodyAndHeaders && bodyStream != null && method.getStatusCode() != 204) { try { InputStream responseBody = method.getResponseBodyAsStream(); if (responseBody != null) { IOUtils.copy(responseBody, filter.getOutputStream()); bodyStream.flush(); bodyStream.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:com.hp.alm.ali.rest.client.AliRestClient.java
private boolean tryLogin(ResultInfo resultInfo, HttpMethod method) { try {// w ww .j a v a2 s . c om login(); return true; } catch (HttpStatusBasedException e) { resultInfo.setHttpStatus(e.getHttpStatus()); resultInfo.setReasonPhrase(e.getReasonPhrase()); try { resultInfo.setLocation(e.getLocation() + " [on-behalf-of: " + method.getURI().toString() + "]"); } catch (URIException e2) { resultInfo.setLocation(e.getLocation() + " [on-behalf-of: " + method.getPath() + "]"); } return false; } }
From source file:com.dtolabs.client.utils.HttpClientChannel.java
private HttpMethod checkFollowRedirect(final HttpMethod method, final int res) throws IOException, HttpClientException { if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) { final Header locHeader = method.getResponseHeader("Location"); if (locHeader == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + method.getURI()); }//from w w w . ja va 2s. c o m final String location = locHeader.getValue(); logger.debug("Follow redirect: " + res + ": " + location); method.releaseConnection(); final GetMethod followMethod = new GetMethod(location); followMethod.setFollowRedirects(true); resultCode = httpc.executeMethod(followMethod); reasonCode = followMethod.getStatusText(); logger.debug("Result: " + resultCode); return followMethod; } return method; }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Writes tracing information that traces the request/response activity. * // w ww. j a v a 2 s.c o m * @param traceLevel * Indicates how much trace info to produce. * @param traceStream * An output stream where trace statements will be written. * @param httpMethod * The HttpMethod object of the request. */ private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) { try { if (traceLevel >= TRACE_URI) { // Show trace output of the request URI traceStream .println("-------------------------------------------------------------------------------"); traceStream.println(httpMethod.getURI() + "\n"); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP request line traceStream.println(httpMethod.getName() + " " + httpMethod.getPath() + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " " + httpMethod.getParams().getVersion().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP request headers for (Header header : httpMethod.getRequestHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } // Show trace of request entity body if (httpMethod instanceof PostMethod) { NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters(); if (parameters != null) { // StringBuffer parameterString = new StringBuffer(); // for (NameValuePair parameter : parameters) { // parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&"); // } // parameterString.deleteCharAt(parameterString.length() - 1); String parameterString = new String( ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity()) .getContent(), "UTF-8"); traceStream.println(" |"); traceStream.println(" +-- " + parameterString); } } traceStream.println(); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP status line traceStream.println(httpMethod.getStatusLine().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP response headers for (Header header : httpMethod.getResponseHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } traceStream.println(); } if (traceLevel >= TRACE_BODY) { // Show trace output of the HTTP response body traceStream.println(httpMethod.getResponseBodyAsString()); traceStream.println(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
protected void copyResponseEntity(HttpMethod method, HttpServletResponse servletResponse) throws IOException { InputStream entity = method.getResponseBodyAsStream(); if (entity != null) { OutputStream servletOutputStream = servletResponse.getOutputStream(); if (servletResponse.getHeader("Content-Type") == null || servletResponse.getHeader("Content-Type").contains("html")) { String inputLine;//from w w w . j a v a2s .com BufferedReader br = new BufferedReader(new InputStreamReader(entity)); try { int contentSize = 0; String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort(); while ((inputLine = br.readLine()) != null) { String outputLine = hopify(inputLine, source) + "\n"; byte[] output = outputLine.getBytes(Charset.forName("UTF-8")); servletOutputStream.write(output); contentSize += output.length; } br.close(); servletResponse.setHeader("Content-Length", Integer.toString(contentSize)); } catch (IOException e) { e.printStackTrace(); } } else { org.apache.hadoop.io.IOUtils.copyBytes(entity, servletOutputStream, 4096, doLog); } } }
From source file:com.ideabase.repository.webservice.client.impl.HttpWebServiceControllerImpl.java
/** * {@inheritDoc}/*from w w w . ja va2s . co m*/ */ public WebServiceResponse sendServiceRequest(final WebServiceRequest pRequest) { if (LOG.isDebugEnabled()) { LOG.debug("Sending request - " + pRequest); } // build query string final NameValuePair[] parameters = buildParameters(pRequest); // Send request to server final HttpMethod httpMethod = prepareMethod(pRequest.getRequestMethod(), pRequest.getServiceUri(), parameters); // set cookie policy httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // set cookies if (mCookies != null) { httpMethod.setRequestHeader(HEADER_COOKIE, mCookies); } if (pRequest.getCookies() != null) { httpMethod.setRequestHeader(HEADER_COOKIE, pRequest.getCookies()); mCookies = pRequest.getCookies(); } // execute method final HttpClient httpClient = new HttpClient(); final WebServiceResponse response; try { final int status = httpClient.executeMethod(httpMethod); // build web sercie response response = new WebServiceResponse(); response.setResponseStatus(status); response.setResponseContent(new String(httpMethod.getResponseBody())); response.setContentType(httpMethod.getResponseHeader(HEADER_CONTENT_TYPE).getValue()); response.setServiceUri(httpMethod.getURI().toString()); // set cookies final Header cookieHeader = httpMethod.getResponseHeader(HEADER_SET_COOKIE); if (cookieHeader != null) { mCookies = cookieHeader.getValue(); } // set cookies to the returning response object. response.setCookies(mCookies); if (LOG.isDebugEnabled()) { LOG.debug("Cookies - " + mCookies); LOG.debug("Response - " + response); } } catch (Exception e) { throw ServiceException.aNew(pRequest, "Failed to send web service request.", e); } finally { httpMethod.releaseConnection(); } return response; }