List of usage examples for org.apache.http.client.methods HttpRequestBase getAllHeaders
public Header[] getAllHeaders()
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Print the HTTP request - for debugging purposes *//* w ww . j a va 2s . c o m*/ @SuppressWarnings("unused") private static void printRequest(HttpRequestBase request) { if (LOGGER.isLoggable(Level.FINER)) { StringBuffer logMessage = new StringBuffer(); logMessage.append(NEW_LINE).append("\t- Method: ").append(request.getMethod()); //$NON-NLS-1$ // logMessage.append(NEW_LINE).append("\t- URL: ").append(request.getURI()); //$NON-NLS-1$ logMessage.append(NEW_LINE).append("\t- Headers: "); //$NON-NLS-1$ Header[] headers = request.getAllHeaders(); for (int i = 0; i < headers.length; i++) { logMessage.append(NEW_LINE).append("\t\t- ").append(headers[i].getName()).append(": ") //$NON-NLS-1$//$NON-NLS-2$ .append(headers[i].getValue()); } LOGGER.finer(logMessage.toString()); } }
From source file:com.andrestrequest.http.DefaultRequestHandler.java
/** * * Make the request to Xively API and return the response string * @param <T extends ConnectedObject> * @param method/*from www . j a v a 2 s . c o m*/ * http request methods * @param path * restful app path * @param body * objects to be parsed as body for api call * @param params * key-value of params for api call * @param headers * @return response string * @throws HttpException */ public synchronized Response doRequest(HttpMethod method, String path, Map<String, String> headers, Object body, Map<String, Object> params) throws Exception { Response response = null; HttpRequestBase request = buildRequest(method, path, headers, body, params); if (DEBUG) { System.out.println(request); for (Header header : request.getAllHeaders()) { System.out.println(header); } if (body != null) { System.out.println(EntityUtils.toString(getEntity(body), AndRestConfig.getCharset())); } } if (responseHandler == null) { responseHandler = new DefaultResponseHandler(); } response = getClient().execute(request, responseHandler); return response; }
From source file:com.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java
/** * * Make the request to Xively API and return the response string * /*ww w. j a v a 2s . c om*/ * @param <T extends ConnectedObject> * * @param method * http request methods * @param path * restful app path * @param body * objects to be parsed as body for api call * @param params * key-value of params for api call * @param headers * * @return response string * @throws HttpException */ public Response doRequest(HttpMethod method, String path, Map<String, String> headers, Object body, Map<String, Object> params) throws HttpException { Response response = null; HttpRequestBase request = buildRequest(method, path, headers, body, params); try { if (DEBUG) { System.out.println(request); for (Header header : request.getAllHeaders()) { System.out.println(header); } if (body != null) { System.out.println(EntityUtils.toString(getEntity(body), AppConfig.getCharset())); } //System.out.println(request.getParams()); } DefaultResponseHandler responseHandler = new DefaultResponseHandler(); response = getClient().execute(request, responseHandler); } catch (IOException e) { throw new HttpException("Http request did not return successfully.", e); // } catch (RuntimeException e) { // // release resources manually on unexpected exceptions // request.abort(); // throw new HttpException( // "Http request did not return successfully.", e); } return response; }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Executes the method and return the result. Handle ask for password * when hitting password protected site. * Keep asking for password till user clicks cancel or enters correct * password. When 'remember password' is checked password is saved, if this * password and username are not correct clear them, if there are correct * they stay saved.//from w ww . ja v a 2s . c om * @param httpClient the configured http client to use. * @param req the request for now it is get or post. * @param redirectHandler handles redirection, should we redirect and * the actual redirect. * @param parameters if we are redirecting we can use already filled * username and password in order to avoid asking the user twice. * * @return the result http entity. */ private static HttpEntity executeMethod(DefaultHttpClient httpClient, HttpRequestBase req, RedirectHandler redirectHandler, List<NameValuePair> parameters) throws Throwable { // do it when response (first execution) or till we are unauthorized HttpResponse response = null; int redirects = 0; while (response == null || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) { // if we were unauthorized, lets clear the method and recreate it // for new connection with new credentials. if (response != null && (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN)) { if (logger.isDebugEnabled()) logger.debug("Will retry http connect and " + "credentials input as latest are not correct!"); throw new AuthenticationException("Authorization needed"); } else response = httpClient.execute(req); // if user click cancel no need to retry, stop trying if (!((HTTPCredentialsProvider) httpClient.getCredentialsProvider()).retry()) { if (logger.isDebugEnabled()) logger.debug("User canceled credentials input."); break; } // check for post redirect as post redirects are not handled // automatically // RFC2616 (10.3 Redirection 3xx). // The second request (forwarded method) can only be a GET or HEAD. Header locationHeader = response.getFirstHeader("location"); if (locationHeader != null && req instanceof HttpPost && (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER) && redirects < MAX_REDIRECTS) { HttpRequestBase oldreq = req; oldreq.abort(); String newLocation = locationHeader.getValue(); // lets ask redirection handler if any if (redirectHandler != null && redirectHandler.handleRedirect(newLocation, parameters)) { return null; } req = new HttpGet(newLocation); req.setParams(oldreq.getParams()); req.setHeaders(oldreq.getAllHeaders()); redirects++; response = httpClient.execute(req); } } // if we finally managed to login return the result. if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response.getEntity(); } // is user has canceled no result needed. return null; }
From source file:org.openlmis.UiUtils.HttpClient.java
private void prepareRequestHeaderAndEntity(String commMethod, String json, HttpRequestBase httpRequest, boolean headerRequired) throws UnsupportedEncodingException { if (commMethod.equals(GET)) return;/* ww w . j a v a 2s . c om*/ httpRequest.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8")); ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new StringEntity(json)); if (!headerRequired) { Header[] headers = httpRequest.getAllHeaders(); for (Header h : headers) { httpRequest.removeHeader(h); } } }
From source file:org.fcrepo.camel.FcrepoClient.java
/** * Make a GET request//from w ww .j a va2 s . co m * @param url the URL of the resource to fetch * @param accept the requested MIMEType of the resource to be retrieved * @param prefer the value for a prefer header sent in the request * @return the repository response * @throws FcrepoOperationFailedException when the underlying HTTP request results in an error */ public FcrepoResponse get(final URI url, final String accept, final String prefer) throws FcrepoOperationFailedException { final HttpRequestBase request = HttpMethods.GET.createRequest(url); if (accept != null) { request.setHeader("Accept", accept); } if (prefer != null) { request.setHeader("Prefer", prefer); } LOGGER.debug("Fcrepo GET request headers: {}", request.getAllHeaders()); final HttpResponse response = executeRequest(request); final int status = response.getStatusLine().getStatusCode(); final String contentType = getContentTypeHeader(response); LOGGER.debug("Fcrepo GET request returned status [{}]", status); if ((status >= HttpStatus.SC_OK && status < HttpStatus.SC_BAD_REQUEST) || !this.throwExceptionOnFailure) { URI describedBy = null; final List<URI> links = getLinkHeaders(response, DESCRIBED_BY); if (links.size() == 1) { describedBy = links.get(0); } return new FcrepoResponse(url, status, contentType, describedBy, getEntityContent(response)); } else { throw new FcrepoOperationFailedException(url, status, response.getStatusLine().getReasonPhrase()); } }
From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java
/** * Execute an HTTP request and return the raw input stream. <i>Caller is responsible for closing InputStream.</i> * * @param path url to issue request to//www . ja v a 2 s . c om * @return raw input stream from response * @throws IOException On error */ @Override public InputStream executeDownloadByteStream(String path) throws IOException { if (this.conn.getConfig() == null) { throw new IllegalStateException("Can't execute HTTP request when configuration is undefined."); } InputStream stream = null; String fullPath = this.conn.getConfig().getTcApiUrl() + path.replace("/api/", "/"); logger.trace("Calling GET: " + fullPath); HttpRequestBase httpBase = getBase(fullPath, HttpMethod.GET); String headerPath = httpBase.getURI().getRawPath() + "?" + httpBase.getURI().getRawQuery(); ConnectionUtil.applyHeaders(this.conn.getConfig(), httpBase, httpBase.getMethod(), headerPath, conn.getConfig().getContentType(), ContentType.APPLICATION_OCTET_STREAM.toString()); logger.trace("Request: " + httpBase.getRequestLine()); logger.trace("Headers: " + Arrays.toString(httpBase.getAllHeaders())); CloseableHttpResponse response = this.conn.getApiClient().execute(httpBase); logger.trace(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); logger.trace(String.format("Result stream size: %d, encoding: %s", entity.getContentLength(), entity.getContentEncoding())); } return stream; }
From source file:com.woonoz.proxy.servlet.HttpRequestHandler.java
public void execute() { UrlRewriter urlRewriter = new UrlRewriterImpl(request, targetServer); ClientHeadersHandler clientHeadersHandler = createClientHeadersHandler(urlRewriter); ServerHeadersHandler serverHeadersHandler = new ServerHeadersHandler(urlRewriter); HttpRequestBase httpCommand = null; try {//from w w w .j av a2 s .c o m logger.debug("Doing rewrite for uri: {}", request.getRequestURL()); final URI targetUri = urlRewriter.rewriteUri(new URI(request.getRequestURL().toString())); logger.debug("Making request for rewritten uri: {}", targetUri); httpCommand = createHttpCommand(targetUri, clientHeadersHandler); logger.debug("Http client command: {}, headers: {}", httpCommand.getRequestLine(), Arrays.asList(httpCommand.getAllHeaders())); performHttpRequest(httpCommand, response, serverHeadersHandler); } catch (URISyntaxException e) { handleException(httpCommand, e); } catch (IOException e) { handleException(httpCommand, e); } catch (InvalidCookieException e) { handleException(httpCommand, e); } catch (FileUploadException e) { handleException(httpCommand, e); } catch (RuntimeException e) { handleException(httpCommand, e); } finally { try { response.getOutputStream().flush(); } catch (IOException e) { logger.error("Exception flushing OutputStream ", e); } } }
From source file:org.fao.geonet.utils.AbstractHttpRequest.java
protected String getSentData(HttpRequestBase httpMethod) { URI uri = httpMethod.getURI(); StringBuilder sentData = new StringBuilder(httpMethod.getMethod()).append(" ").append(uri.getPath()); if (uri.getQuery() != null) { sentData.append("?" + uri.getQuery()); }/*from ww w . j a va 2 s .c o m*/ sentData.append("\r\n"); for (Header h : httpMethod.getAllHeaders()) { sentData.append(h); } sentData.append("\r\n"); if (httpMethod instanceof HttpPost) { sentData.append(postData); } return sentData.toString(); }