List of usage examples for org.apache.commons.httpclient HttpMethod getURI
public abstract URI getURI() throws URIException;
From source file:com.adobe.share.api.ShareAPI.java
/** * Parses the response from the Share service. * * @param method the method/* w w w .j av a2 s.com*/ * * @return the jSON object * * @throws HttpException the http exception * @throws IOException Signals that an I/O exception has occurred. * @throws ShareAPIException the share api exception */ protected final JSONObject parseResponse(final HttpMethod method) throws HttpException, IOException, ShareAPIException { JSONObject json = null; String content = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("URL: " + method.getURI().toString()); LOGGER.debug("Proxy: " + httpClient.getHostConfiguration().getProxyHost()); LOGGER.debug("Proxy Port: " + httpClient.getHostConfiguration().getProxyPort()); } try { int status = httpClient.executeMethod(method); final int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; OutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = method.getResponseBodyAsStream(); while (true) { int read = inputStream.read(buffer); if (read == -1) { break; } outputStream.write(buffer, 0, read); } outputStream.close(); inputStream.close(); content = outputStream.toString(); if (method.getResponseHeader("Content-Type") != null) { String contentType = method.getResponseHeader("Content-Type").getValue(); if (method.getStatusCode() == STATUS_OK) { if (contentType.contains("application/xml")) { json = XML.toJSONObject(content); } } } if (status >= STATUS_BAD_REQUEST) { if (json != null) { throw new ShareAPIException(method.getStatusCode(), json.getJSONObject("response").getString("message")); } else { throw new ShareAPIException(method.getStatusCode(), content); } } } catch (JSONException e) { e.printStackTrace(); throw new ShareAPIException(method.getStatusCode(), content); } return json; }
From source file:net.oauth.client.httpclient3.HttpClient3.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod; if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt();/*ww w. j a v a 2s. c o m*/ } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
From source file:mitm.common.net.HTTPMethodExecutor.java
protected void internalExecuteMethod(HttpMethod httpMethod, ResponseHandler responseHandler, TaskScheduler watchdog) throws IOException { HttpClient httpClient = createHttpClient(); HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams(); if (connectTimeout > 0) { params.setConnectionTimeout(connectTimeout); }//from w w w. j av a2s.c o m if (readTimeout > 0) { params.setSoTimeout(readTimeout); } if (proxyInjector != null) { try { proxyInjector.setProxy(httpClient); } catch (ProxyException e) { throw new IOException(e); } } initDefaultSettings(httpMethod); /* * Add last resort watchdog that will interrupt the thread on timeout. we want the abort the HTTP method * first so add 50% to totalTimeout. */ Task threadWatchdogTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName()); watchdog.addTask(threadWatchdogTask, (long) (totalTimeout * 1.5)); /* * Add watchdog that will abort the HTTPMethod on timeout. */ Task httpMethodAbortTimeoutTask = new HTTPMethodAbortTimeoutTask(httpMethod, watchdog.getName()); watchdog.addTask(httpMethodAbortTimeoutTask, (long) (totalTimeout)); try { logger.debug("Setting up a connection to: " + httpMethod.getURI()); int statusCode = 0; try { statusCode = httpClient.executeMethod(httpMethod); } catch (IllegalArgumentException e) { /* * HttpClient can throw IllegalArgumentException when the host is not set */ throw new IOException(e); } responseHandler.handleResponse(statusCode, httpMethod, watchdog); if (threadWatchdogTask.hasRun() || httpMethodAbortTimeoutTask.hasRun()) { /* * a timeout has occurred. In most cases, a exception was probably already thrown because the * connection was forcefully closed. */ throw new IOException(TIMEOUT_ERROR + httpMethod.getURI()); } } finally { httpMethod.releaseConnection(); } }
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchConnector.java
public int executeMethod(HttpMethod method) throws IndexStoreException, IOException { String reqBody = ""; if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eem = (EntityEnclosingMethod) method; RequestEntity re = eem.getRequestEntity(); if (re instanceof StringRequestEntity) { StringRequestEntity sre = (StringRequestEntity) re; reqBody = Strings.nullToEmpty(sre.getContent()); if (reqBody.length() > 0) { reqBody = String.format("\nREQUEST BODY=%s", reqBody); }//from ww w. jav a 2 s. c om } } try { HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); statusCode = client.executeMethod(method); } catch (ConnectException ce) { throw new ZimbraElasticSearchDownException(ce); } catch (NoHttpResponseException nhre) { // managed to connect to the ElasticSearch service but it either crashed or timed out before // we got sent back the response. // Could be a temporary problem or a problem with this particular request. // In the longer term we need to track failures related to particular items at a higher level and discard // them after retrying a number of times. throw new ZimbraElasticSearchNoResponseException(nhre); } body = method.getResponseBodyAsString(); ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body); return statusCode; }
From source file:ensen.controler.AnnotationClient.java
public String request(HttpMethod method) throws AnnotationException { String response = null;//www. j ava 2 s . co m // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("Method failed: " + method.getStatusLine()); } // Read the response body. InputStream responseBodyStream = method.getResponseBodyAsStream(); //Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended. int b = responseBodyStream.read(); ArrayList<Integer> bytes = new ArrayList<Integer>(); while (b != -1) { bytes.add(b); b = responseBodyStream.read(); } byte[] responseBody = new byte[bytes.size()]; for (int i = 0; i < bytes.size(); i++) { responseBody[i] = bytes.get(i).byteValue(); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary data response = new String(responseBody); } catch (HttpException e) { System.out.println("Fatal protocol violation: " + e.getMessage()); try { System.err.println(method.getURI()); } catch (URIException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } throw new AnnotationException("Protocol error executing HTTP request.", e); } catch (IOException e) { System.out.println("Fatal transport error: " + e.getMessage()); System.out.println(method.getQueryString()); throw new AnnotationException("Transport error executing HTTP request.", e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.groupon.odo.Proxy.java
/** * Log modified request//w w w . j a v a 2 s . c om * * @param httpMethodProxyRequest * @param httpServletResponse * @param history */ private void logRequestHistory(HttpMethod httpMethodProxyRequest, HttpServletResponse httpServletResponse, History history) { try { if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) { logger.info("Storing history"); String createdDate; SimpleDateFormat sdf = new SimpleDateFormat(); sdf.setTimeZone(new SimpleTimeZone(0, "GMT")); sdf.applyPattern("dd MMM yyyy HH:mm:ss"); createdDate = sdf.format(new Date()) + " GMT"; history.setCreatedAt(createdDate); history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? "" : httpMethodProxyRequest.getQueryString()); history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest)); history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse)); history.setResponseCode(Integer.toString(httpServletResponse.getStatus())); history.setResponseContentType(httpServletResponse.getContentType()); history.setResponseData(requestInformation.get().outputString); HistoryService.getInstance().addHistory(history); logger.info("Done storing"); } } catch (URIException e) { e.printStackTrace(); } }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private void submitHttpRequest(String address, MessageObject mo) throws Exception { HttpMethod httpMethod = null; try {//from ww w. j av a2s .c o m httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo); // authentication if (connector.isDispatcherUseAuthentication()) { List<String> authenticationPreferences = new ArrayList<String>(); if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) { authenticationPreferences.add(AuthPolicy.DIGEST); logger.debug("using Digest authentication"); } else { authenticationPreferences.add(AuthPolicy.BASIC); logger.debug("using Basic authentication"); } client.getParams().setAuthenticationPreemptive(true); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences); Credentials credentials = new UsernamePasswordCredentials( replacer.replaceValues(connector.getDispatcherUsername(), mo), replacer.replaceValues(connector.getDispatcherPassword(), mo)); client.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials); logger.debug("using authentication with credentials: " + credentials); } client.getParams().setSoTimeout( NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000)); // execute the method logger.debug( "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString()); int statusCode = client.executeMethod(httpMethod); logger.debug("received status code: " + statusCode); String response = null; if (connector.isDispatcherIncludeHeadersInResponse()) { HttpMessageConverter converter = new HttpMessageConverter(); response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(), httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString()); } else { response = httpMethod.getResponseBodyAsString(); } if (statusCode < HttpStatus.SC_BAD_REQUEST) { messageObjectController.setSuccess(mo, response, null); // send to reply channel if ((connector.getDispatcherReplyChannelId() != null) && !connector.getDispatcherReplyChannelId().equals("sink")) { new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true); } } else { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404, "Received error response from HTTP server.", null); messageObjectController.setError(mo, Constants.ERROR_404, response, null, null); } } catch (Exception e) { throw e; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:net.sourceforge.jwbf.actions.HttpActionClient.java
/** * Process a POST Message./*w ww . j av a 2 s. c om*/ * * @param authpost * a * @param cp * a * @return a returning message, not null * @throws IOException on problems * @throws ProcessException on problems * @throws CookieException on problems */ protected String post(HttpMethod authpost, ContentProcessable cp) throws IOException, ProcessException, CookieException { showCookies(client); authpost.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET); String out = ""; client.executeMethod(authpost); // Header locationHeader = authpost.getResponseHeader("location"); // if (locationHeader != null) { // authpost.setRequestHeader(locationHeader) ; // } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } LOG.debug("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); LOG.debug("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); authpost = redirect; } } out = authpost.getResponseBodyAsString(); out = cp.processReturningText(out, authpost); cp.validateReturningCookies(client.getState().getCookies(), authpost); authpost.releaseConnection(); LOG.debug(authpost.getURI() + " || " + "POST: " + authpost.getStatusLine().toString()); return out; }
From source file:ch.ksfx.web.services.spidering.http.WebEngine.java
public void loadResource(Resource resource) { HttpMethod httpMethod; try {//from www.j a v a 2 s. co m if (/*resource.getHttpMethod().equals(GET)*/true) { String url = resource.getUrl(); if (url != null) { url = url.replaceAll("&", "&"); url = url.replaceAll(""", "\""); } httpMethod = this.httpClientHelper.executeGetMethod(url); } else { //TODO implement POST functionality /* NameValuePair[] nameValuePairs = new NameValuePair[resource.getPostData().size()]; for(int i = 0; i < resource.getPostData().size(); i++) { nameValuePairs[i] = new NameValuePair(resource.getPostData().get(i).getName(), resource.getPostData().get(i).getValue()); } String url = resource.getURL().toString(); if (url != null) { url = url.replaceAll("&","&"); url = url.replaceAll(""","\""); } httpMethod = this.httpClientHelper.executePostMethod(url, nameValuePairs); */ } } catch (Exception e) { resource.setLoadSucceed(false); resource.setHttpStatusCode(222); logger.log(Level.SEVERE, "Unable to load resource", e); return; } if (httpMethod == null) { resource.setLoadSucceed(false); return; } if (httpMethod.getStatusCode() != HttpStatus.SC_OK) { try { resource.setUrl(httpMethod.getURI().toString()); for (Header header : httpMethod.getResponseHeaders()) { resource.addResponseHeader(new ResponseHeader(header.getName(), header.getValue())); } resource.setHttpStatusCode(httpMethod.getStatusCode()); } catch (Exception e) { logger.warning(e.getMessage()); e.printStackTrace(); } return; } try { if (httpMethod.getResponseHeader("Content-Encoding") != null && httpMethod.getResponseHeader("Content-Encoding").getValue().contains("gzip")) { BufferedInputStream in = new BufferedInputStream( new GZIPInputStream(httpMethod.getResponseBodyAsStream())); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) >= 0) { out.write(buffer, 0, length); } resource.setRawContent(out.toByteArray()); resource.setSize(new Long(out.toByteArray().length)); } else { BufferedInputStream in = new BufferedInputStream(httpMethod.getResponseBodyAsStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) >= 0) { out.write(buffer, 0, length); } resource.setRawContent(out.toByteArray()); resource.setSize(new Long(out.toByteArray().length)); } resource.setHttpStatusCode(httpMethod.getStatusCode()); resource.setLoadSucceed(true); resource.setMimeType(recognizeMimeType(resource, httpMethod)); if (resource.getMimeType().startsWith("text") || resource.getMimeType().equals("application/json")) { resource.setContent(EncodingHelper.encode(resource.getRawContent(), resource.getEncoding(), ((HttpMethodBase) httpMethod).getResponseCharSet())); } else { resource.setIsBinary(true); } } catch (IOException e) { e.printStackTrace(); logger.log(Level.SEVERE, "Unable to load resource", e); } finally { httpMethod.releaseConnection(); } }
From source file:com.groupon.odo.Proxy.java
/** * Execute a request//from w w w . j a v a2 s .c om * * @param httpMethodProxyRequest * @param httpServletRequest * @param httpServletResponse * @param history * @param outStream * @throws Exception */ private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception { int intProxyResponseCode = 999; try { // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); ArrayList<String> headersToRemove = getRemoveHeaders(); httpClient.getParams().setSoTimeout(60000); httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove); intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); } catch (Exception e) { requestInformation.get().outputString = "TIMEOUT"; logRequestHistory(httpMethodProxyRequest, httpServletResponse, history); throw e; } logger.info("Response code: {}, {}", intProxyResponseCode, HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse); } else { // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // there is no data for a HTTP 304 if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); int intNextByte; // Collect all of the server data while ((intNextByte = bufferedInputStream.read()) != -1) { outStream.write(intNextByte); } } } }