List of usage examples for org.apache.commons.httpclient HttpMethodBase getURI
@Override public URI getURI() throws URIException
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//from ww w . j av a 2 s. c om * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HttpMethodBase httpMethod = null; HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time try { // May generate IllegalArgumentException if (method.equals(HTTPConstants.POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(HTTPConstants.GET)) { httpMethod = new GetMethod(urlStr); } else if (method.equals(HTTPConstants.PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HTTPConstants.HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(HTTPConstants.TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(HTTPConstants.OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(HTTPConstants.DELETE)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.DELETE; } }; } else if (method.equals(HTTPConstants.PATCH)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.PATCH; } }; } else { throw new IllegalArgumentException("Unexpected method: '" + method + "'"); } final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection HttpClient client = setupConnection(url, httpMethod, res); savedClient = client; // Handle the various methods if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData((PostMethod) httpMethod); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH) || method.equals(HTTPConstants.DELETE)) { String putBody = sendEntityData((EntityEnclosingMethod) httpMethod); res.setQueryString(putBody); } int statusCode = client.executeMethod(httpMethod); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = client.getHostConfiguration().getLocalAddress(); if (localAddr != null) { httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: InputStream instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD instream = new CountingInputStream(instream); try { Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) { InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting res.setResponseData( readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength())); } else { res.setResponseData( readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } } finally { JOrphanUtils.closeQuietly(instream); } } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); // in case sanitising fails } // record some sizes to allow HTTPSampleResult.getBytes() with different options if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); } res.setHeadersSize(calculateHeadersSize(httpMethod)); if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod can be null if method is unexpected if (httpMethod != null) { res.setRequestHeaders(getConnectionHeaders(httpMethod)); } errorResult(e, res); return res; } catch (IOException e) { res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod cannot be null here, otherwise // it would have been caught in the previous catch block res.setRequestHeaders(getConnectionHeaders(httpMethod)); errorResult(e, res); return res; } finally { savedClient = null; if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//from ww w. ja va 2 s . co m * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toExternalForm(); // Check if this is an entity-enclosing method boolean isPost = method.equals(POST) || method.equals(PUT); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); // Handles OAuth signing try { message = getOAuthMessage(url, method); urlStr = message.URL; if (isPost) { urlStr = message.URL; } else { if (useAuthHeader) urlStr = OAuth.addParameters(message.URL, nonOAuthParams); else urlStr = OAuth.addParameters(message.URL, message.getParameters()); } } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (OAuthException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (URISyntaxException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } log.debug("Start : sample " + urlStr); //$NON-NLS-1$ log.debug("method " + method); //$NON-NLS-1$ HttpMethodBase httpMethod = null; res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // May generate IllegalArgumentException if (method.equals(POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(DELETE)) { httpMethod = new DeleteMethod(urlStr); } else if (method.equals(GET)) { httpMethod = new GetMethod(urlStr); } else { log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$ httpMethod = new GetMethod(urlStr); } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(new URL(urlStr), httpMethod, res); // Handle POST and PUT if (isPost) { String postBody = sendPostData(httpMethod); res.setQueryString(postBody); } res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = client.executeMethod(httpMethod); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$ } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); //$NON-NLS-1$ httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java
protected void handleReturnCode(int code, HttpMethodBase method) throws CoreException { try {//w w w . j a va 2 s. com if (code == java.net.HttpURLConnection.HTTP_OK) { return;// Status.OK_STATUS; } else if (code == java.net.HttpURLConnection.HTTP_MOVED_TEMP || code == java.net.HttpURLConnection.HTTP_CREATED) { // A new resource created... return;// Status.OK_STATUS; } else if (code == java.net.HttpURLConnection.HTTP_UNAUTHORIZED || code == java.net.HttpURLConnection.HTTP_FORBIDDEN) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Unable to log into server, ensure repository credentials are correct.")); //$NON-NLS-1$ } else if (code == java.net.HttpURLConnection.HTTP_PRECON_FAILED) { // Mid-air collision throw new CoreException( new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Mid-air collision occurred.")); //$NON-NLS-1$ } else if (code == java.net.HttpURLConnection.HTTP_CONFLICT) { throw new CoreException( new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "A conflict occurred.")); //$NON-NLS-1$ } else { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Unknown error occurred. Http Code: " + code + " Request: " + method.getURI() //$NON-NLS-1$//$NON-NLS-2$ + " Response: " //$NON-NLS-1$ + method.getResponseBodyAsString())); } } catch (URIException e) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$ + e.getMessage())); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$ + e.getMessage())); } }
From source file:org.elasticsearch.hadoop.rest.RestClient.java
byte[] execute(HttpMethodBase method, boolean checkStatus) { try {/* w w w .j a va 2 s. c o m*/ int status = client.executeMethod(method); if (checkStatus && status >= HttpStatus.SC_MULTI_STATUS) { String body; try { body = method.getResponseBodyAsString(); } catch (IOException ex) { body = ""; } throw new IllegalStateException(String.format("[%s] on [%s] failed; server[%s] returned [%s]", method.getName(), method.getURI(), client.getHostConfiguration().getHostURL(), body)); } return method.getResponseBody(); } catch (IOException io) { String target; try { target = method.getURI().toString(); } catch (IOException ex) { target = method.getPath(); } throw new IllegalStateException( String.format("Cannot get response body for [%s][%s]", method.getName(), target)); } finally { method.releaseConnection(); } }
From source file:org.folg.werelatedata.editor.PageEditor.java
private String getResponse(HttpMethodBase m) throws IOException { InputStream s = m.getResponseBodyAsStream(); int bytesRead = -1; int totalBytes = 0; int bytesToRead = BUF_SIZE; byte[] buf = new byte[BUF_SIZE]; while (true) { bytesRead = s.read(buf, totalBytes, bytesToRead); if (bytesRead < 0) { break; }//from ww w. ja v a 2 s .c o m totalBytes += bytesRead; bytesToRead -= bytesRead; if (bytesToRead == 0) { // buffer full, so allocate more if (buf.length * 2 > MAX_BUF_SIZE) { throw new IOException("Response too long: " + m.getURI().toString()); } byte[] temp = buf; buf = new byte[temp.length * 2]; System.arraycopy(temp, 0, buf, 0, temp.length); bytesToRead = temp.length; } } if (totalBytes > 0) { return EncodingUtil.getString(buf, 0, totalBytes, m.getResponseCharSet()); } else { return null; } }
From source file:org.geotools.data.wfs.protocol.http.DefaultHTTPProtocol.java
/** * /*www .j av a 2s . c o m*/ * @param httpRequest * either a {@link HttpMethod} or {@link PostMethod} set up with the request to be * sent * @return * @throws IOException */ private HTTPResponse issueRequest(final HttpMethodBase httpRequest) throws IOException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Executing HTTP request: " + httpRequest.getURI()); } if (client == null) { client = new HttpClient(); client.getParams().setParameter("http.useragent", "GeoTools " + GeoTools.getVersion() + " WFS DataStore"); } if (timeoutMillis > 0) { client.getParams().setSoTimeout(timeoutMillis); } // TODO: remove this System.err.println("Executing HTTP request: " + httpRequest); if (isTryGzip()) { LOGGER.finest("Adding 'Accept-Encoding=gzip' header to request"); httpRequest.addRequestHeader("Accept-Encoding", "gzip"); } int statusCode; try { statusCode = client.executeMethod(httpRequest); } catch (IOException e) { httpRequest.releaseConnection(); throw e; } if (statusCode != HttpStatus.SC_OK) { httpRequest.releaseConnection(); String statusText = HttpStatus.getStatusText(statusCode); throw new IOException("Request failed with status code " + statusCode + "(" + statusText + "): " + httpRequest.getURI()); } HTTPResponse httpResponse = new HTTPClientResponse(httpRequest); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Got " + httpResponse); } return httpResponse; }
From source file:org.jboss.ejb3.test.clusteredservice.unit.HttpUtils.java
public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type) throws Exception { HttpClient httpConn = new HttpClient(); HttpMethodBase request = createMethod(url, type); int hdrCount = hdrs != null ? hdrs.length : 0; for (int n = 0; n < hdrCount; n++) request.addRequestHeader(hdrs[n]); try {//from www . j a va 2 s .co m log.debug("Connecting to: " + url); String userInfo = url.getUserInfo(); if (userInfo != null) { UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo); httpConn.getState().setCredentials(realm, url.getHost(), auth); } log.debug("RequestURI: " + request.getURI()); int responseCode = httpConn.executeMethod(request); String response = request.getStatusText(); log.debug("responseCode=" + responseCode + ", response=" + response); String content = request.getResponseBodyAsString(); log.debug(content); // Validate that we are seeing the requested response code if (responseCode != expectedHttpCode) { throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode); } } catch (IOException e) { throw e; } return request; }
From source file:org.jboss.test.jpa.test.AbstractWebJPATest.java
public String accessURL(String url) throws Exception { HttpClient httpConn = new HttpClient(); HttpMethodBase request = new GetMethod(baseURL + url); log.debug("RequestURI: " + request.getURI()); int responseCode = httpConn.executeMethod(request); String response = request.getStatusText(); log.debug("responseCode=" + responseCode + ", response=" + response); String content = request.getResponseBodyAsString(); log.debug(content);//ww w . j a v a 2s . co m assertEquals(HttpURLConnection.HTTP_OK, responseCode); return content; }
From source file:org.jboss.test.util.web.HttpUtils.java
public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type) throws Exception { HttpClient httpConn = new HttpClient(); HttpMethodBase request = createMethod(url, type); int hdrCount = hdrs != null ? hdrs.length : 0; for (int n = 0; n < hdrCount; n++) request.addRequestHeader(hdrs[n]); try {/*from w ww .j a v a 2s . c o m*/ log.debug("Connecting to: " + url); String userInfo = url.getUserInfo(); if (userInfo != null) { UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo); httpConn.getState().setCredentials(realm, url.getHost(), auth); } log.debug("RequestURI: " + request.getURI()); int responseCode = httpConn.executeMethod(request); String response = request.getStatusText(); log.debug("responseCode=" + responseCode + ", response=" + response); String content = request.getResponseBodyAsString(); log.debug(content); // Validate that we are seeing the requested response code if (responseCode != expectedHttpCode) { throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode); } } catch (IOException e) { throw e; } return request; }
From source file:org.portletbridge.mock.MockHttpClientTemplate.java
public Object service(HttpMethodBase method, HttpClientState state, HttpClientCallback callback) throws ResourceException { try {// ww w . j a va 2s. c om return callback.doInHttpClient(statusCode, new GetMethod(method.getURI().toString()) { public InputStream getResponseBodyAsStream() throws IOException { return responseBody; } public String getResponseCharSet() { return responseCharSet; } /* (non-Javadoc) * @see org.apache.commons.httpclient.HttpMethodBase#getResponseHeader(java.lang.String) */ public Header getResponseHeader(String name) { String headerValue = (String) responseHeaders.get(name); if (headerValue != null) { Header header = new Header(name, headerValue); return header; } else { return null; } } }); } catch (Throwable e) { throw new ResourceException("error.httpclient", e.getMessage(), e); } }