List of usage examples for org.apache.commons.httpclient HttpMethodBase getStatusLine
@Override
public StatusLine getStatusLine()
From source file:de.avanux.livetracker.sender.LocationSender.java
private String executeHttpMethod(HttpMethodBase method) { String response = null;//from w w w .ja v a2 s. c om HttpClient client = new HttpClient(); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); response = new String(responseBody); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.sittinglittleduck.DirBuster.Worker.java
private String getHeadersAsString(HttpMethodBase httpMethod) { Header[] headers = httpMethod.getResponseHeaders(); StringBuilder builder = new StringBuilder(20 * (headers.length + 1)); builder.append(httpMethod.getStatusLine()); builder.append("\r\n"); for (Header header : headers) { builder.append(header.getName()).append(": ").append(header.getValue()); builder.append("\r\n"); }// w ww.j av a 2 s.c om return builder.append("\r\n").toString(); }
From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java
private void assertResponseCodeOK(HttpMethodBase method, int statusCode) throws HttpException { if (statusCode != HttpStatus.SC_OK) { throw new HttpException("Method failed: " + method.getStatusLine()); }//ww w .j a v a2s . c o m }
From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java
private void assertResponseCodeOK(HttpMethodBase method, int statusCode) throws HttpException { if (statusCode != HttpStatus.SC_OK) { if (log.isTraceEnabled()) { try { log.debug("Method call ended in " + statusCode + "; response page: " + method.getResponseBodyAsString()); } catch (IOException e) { log.error("failed to read body", e); }/* w ww . j a va 2 s.c o m*/ } throw new HttpException("Method failed: " + method.getStatusLine()); } }
From source file:com.comcast.cats.jenkins.service.AbstractService.java
/** * Sends Http request to Jenkins server and read the respose. * /* w ww.j a v a 2 s.c o m*/ * @param mapperClass * @param domainObject * @param client * @param request * @return * @throws NumberFormatException * @throws IOException * @throws HttpException * @throws URIException */ private Object sendRequestToJenkins(Class<?> mapperClass, Object domainObject, HttpClient client, HttpMethodBase request, String apiToken) throws NumberFormatException, IOException, HttpException, URIException { String passwdord = apiToken; if (apiToken.isEmpty()) { // Set jenkins password if no API token is present passwdord = jenkinsClientProperties.getJenkinsPassword(); } client.getState().setCredentials( new AuthScope(jenkinsClientProperties.getJenkinsHost(), new Integer(jenkinsClientProperties.getJenkinsPort()), AuthScope.ANY_REALM), new UsernamePasswordCredentials(jenkinsClientProperties.getJenkinsUsername(), passwdord)); if (!apiToken.isEmpty()) { client.getParams().setAuthenticationPreemptive(true); } int responseCode = client.executeMethod(request); LOGGER.info("[REQUEST][" + request.getURI().toString() + "]"); LOGGER.info("[STATUS][" + request.getStatusLine().toString() + "]"); if (HttpStatus.SC_OK == responseCode) { try { Serializer serializer = new Persister(); domainObject = serializer.read(mapperClass, request.getResponseBodyAsStream(), false); } catch (Exception e) { LOGGER.error(e.getMessage()); } } return domainObject; }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Executes the HTTP request.//ww w. j ava 2 s . c o m * @throws IOException if an Exception occurs */ public void execute() throws IOException { // initialize this.executionLog.setLength(0); StringBuffer log = this.executionLog; ResponseInfo respInfo = this.getResponseInfo(); respInfo.reset(); InputStream responseStream = null; HttpMethodBase method = null; try { log.append("HTTP Client Request\n").append(this.getUrl()); // make the Apache HTTPClient HttpClient client = this.batchHttpClient; if (client == null) { client = new HttpClient(); boolean alwaysClose = Val.chkBool(Val.chkStr(ApplicationContext.getInstance().getConfiguration() .getCatalogConfiguration().getParameters().getValue("httpClient.alwaysClose")), false); if (alwaysClose) { client.setHttpConnectionManager(new SimpleHttpConnectionManager(true)); } } // setting timeout info client.getHttpConnectionManager().getParams().setConnectionTimeout(getConnectionTimeOutMs()); client.getHttpConnectionManager().getParams().setSoTimeout(getResponseTimeOutMs()); // setting retries int retries = this.getRetries(); // create the client and method, apply authentication and proxy settings method = this.createMethod(); //method.setFollowRedirects(true); if (retries > -1) { // TODO: not taking effect yet? DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, true); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); } this.applyAuthAndProxySettings(client, this.getUrl()); // execute the method, determine basic information about the response respInfo.setResponseCode(client.executeMethod(method)); this.determineResponseInfo(method); // collect logging info if (LOGGER.isLoggable(Level.FINER)) { log.append("\n>>").append(method.getStatusLine()); log.append("\n--Request Header"); for (Header hdr : method.getRequestHeaders()) { log.append("\n ").append(hdr.getName() + ": " + hdr.getValue()); } log.append("\n--Response Header"); for (Header hdr : method.getResponseHeaders()) { log.append("\n ").append(hdr.getName() + ": " + hdr.getValue()); } //log.append(" responseCode=").append(this.getResponseInfo().getResponseCode()); //log.append(" responseContentType=").append(this.getResponseInfo().getContentType()); //log.append(" responseContentEncoding=").append(this.getResponseInfo().getContentEncoding()); //log.append(" responseContentLength=").append(this.getResponseInfo().getContentLength()); if (this.getContentProvider() != null) { String loggable = this.getContentProvider().getLoggableContent(); if (loggable != null) { log.append("\n--Request Content------------------------------------\n").append(loggable); } } } // throw an exception if an error is encountered if ((respInfo.getResponseCode() < 200) || (respInfo.getResponseCode() >= 300)) { String msg = "HTTP Request failed: " + method.getStatusLine(); if (respInfo.getResponseCode() == HttpStatus.SC_UNAUTHORIZED) { AuthState authState = method.getHostAuthState(); AuthScheme authScheme = authState.getAuthScheme(); HttpClient401Exception authException = new HttpClient401Exception(msg); authException.setUrl(this.getUrl()); authException.setRealm(authState.getRealm()); authException.setScheme(authScheme.getSchemeName()); if ((authException.getRealm() == null) || (authException.getRealm().length() == 0)) { authException.setRealm(authException.generateHostBasedRealm()); } throw authException; } else { throw new HttpClientException(respInfo.getResponseCode(), msg); } } // handle the response if (this.getContentHandler() != null) { if (getContentHandler().onBeforeReadResponse(this)) { responseStream = getResponseStream(method); if (responseStream != null) { this.getContentHandler().readResponse(this, responseStream); } } // log thre response content String loggable = this.getContentHandler().getLoggableContent(); long nBytesRead = this.getResponseInfo().getBytesRead(); long nCharsRead = this.getResponseInfo().getCharactersRead(); if ((nBytesRead >= 0) || (nCharsRead >= 0) || (loggable != null)) { log.append("\n--Response Content------------------------------------"); if (nBytesRead >= 0) log.append("\n(").append(nBytesRead).append(" bytes read)"); if (nCharsRead >= 0) log.append("\n(").append(nCharsRead).append(" characters read)"); if (loggable != null) log.append("\n").append(loggable); } } } finally { // cleanup try { if (responseStream != null) responseStream.close(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Unable to close HTTP response stream.", t); } try { if (method != null) method.releaseConnection(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Unable to release HttpMethod", t); } // log the request/response if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(this.getExecutionLog().toString()); } } }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page.// w w w .ja v a 2s . c om */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Calculate response headers size/*w w w .ja v a2s . co m*/ * * @return the size response headers (in bytes) */ private static int calculateHeadersSize(HttpMethodBase httpMethod) { int headerSize = httpMethod.getStatusLine().toString().length() + 2; // add a \r\n Header[] rh = httpMethod.getResponseHeaders(); for (Header responseHeader : rh) { headerSize += responseHeader.toString().length(); // already include the \r\n } headerSize += 2; // last \r\n before response data return headerSize; }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient.java
ErrorHandler createErrorHandler() { return new ErrorHandler() { @Override//ww w . j a v a 2s . c o m public void handleError(HttpMethodBase method) throws GerritException { throw new GerritException(method.getStatusLine().getReasonPhrase()); } }; }
From source file:org.genemania.util.HttpRetriever.java
public String post(String url, Hashtable<String, String> params) { String ret = ""; try {/*from ww w.j a va 2 s . co m*/ HttpClient client = new HttpClient(); HttpMethodBase method = new PostMethod(url); Enumeration<String> paramNames = params.keys(); while (paramNames.hasMoreElements()) { String nextParamName = paramNames.nextElement(); String nextParamValue = params.get(nextParamName); ((PostMethod) (method)).addParameter(nextParamName, nextParamValue); } int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("HttpRetriever error: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); method.releaseConnection(); ret = new String(responseBody); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }