List of usage examples for org.apache.http.client.methods HttpEntityEnclosingRequestBase HttpEntityEnclosingRequestBase
public HttpEntityEnclosingRequestBase()
From source file:com.googlecode.noweco.calendar.test.CalendarClientTest.java
@Test @Ignore//from w w w . j a v a 2 s. co m public void test() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // if (google || chandlerproject) { // HttpParams params = httpclient.getParams(); // ConnRouteParams.setDefaultProxy(params, new HttpHost("ecprox.bull.fr")); // } HttpEntityEnclosingRequestBase httpRequestBase = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return "PROPFIND"; } }; BasicHttpEntity entity = new BasicHttpEntity(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream); // outputStreamWriter.write( "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\"> <D:prop> <D:displayname/> <D:principal-collection-set/> <calendar-home-set xmlns=\"urn:ietf:params:xml:ns:caldav\"/> </D:prop> </D:propfind>"); outputStreamWriter.close(); entity.setContent(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); httpRequestBase.setEntity(entity); httpRequestBase.setURI(new URI("/dav/collection/gael.lalire@bull.com/")); if (google) { httpRequestBase.setURI(new URI("/calendar/dav/gael.lalire@gmail.com/user/")); } if (chandlerproject) { httpRequestBase.setURI(new URI("/dav/collection/8de93530-8796-11e0-82b8-d279848d8f3e")); } if (apple) { httpRequestBase.setURI(new URI("/")); } HttpHost target = new HttpHost("localhost", 8080); if (google) { target = new HttpHost("www.google.com", 443, "https"); } if (chandlerproject) { target = new HttpHost("hub.chandlerproject.org", 443, "https"); } if (apple) { target = new HttpHost("localhost", 8008, "http"); } httpRequestBase.setHeader("Depth", "0"); String userpass = null; if (apple) { userpass = "admin:admin"; } httpRequestBase.setHeader("authorization", "Basic " + Base64.encodeBase64String(userpass.getBytes())); HttpResponse execute = httpclient.execute(target, httpRequestBase); System.out.println(Arrays.deepToString(execute.getAllHeaders())); System.out.println(execute.getStatusLine()); System.out.println(EntityUtils.toString(execute.getEntity())); }
From source file:com.robustaweb.library.rest.client.implementation.AndroidRestClient.java
/** * {@inheritDoc }// w ww. j a v a 2 s . co m */ @Override protected void executeMethod(final HttpMethod method, final String url, final String requestBody, final Callback callback) throws HttpException { requestThread = new Thread() { @Override public void run() { HttpRequestBase meth = null; try { switch (method) { case GET: meth = new HttpGet(url); break; case POST: meth = new HttpPost(url); break; case DELETE: meth = new HttpDelete(url); break; case PUT: meth = new HttpPut(url); break; default: meth = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method.getMethod(); } }; break; } // this.builder = new RequestBuilder(meth, url); if (contentType != null && !contentType.isEmpty()) { meth.addHeader("Content-Type", contentType); } if (AndroidRestClient.authorizationValue != null && AndroidRestClient.authorizationValue.length() > 0) { meth.addHeader("Authorization", AndroidRestClient.authorizationValue); } HttpContext localContext = new BasicHttpContext(); HttpResponse response = client.execute(meth, localContext); callback.onSuccess(response.toString()); // headers response HeaderIterator it = response.headerIterator(); while (it.hasNext()) { Header header = it.nextHeader(); responseHeaders.put(header.getName(), header.getValue()); } } catch (Exception ex) { callback.onException(ex); } finally { clean(); } } }; }
From source file:com.web.server.ProxyServlet.java
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);/*from www . ja va 2 s. c o m*/ uri.append(req.getRequestURI()); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:org.gnode.wda.server.ProxyServlet.java
License:asdf
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);/*from ww w . j a va2 s .co m*/ // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method. // Turns "/proxy/asdf" into "/asdf" uri.append(req.getRequestURI().substring(6)); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); if (entity == null) return; InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); if (req.getParameter("update") != null) { uri.append(targetUri).append("/").append(req.getParameter("update")); } else {//from w ww . j a v a2 s. c o m uri.append(targetUri); } LOG.info("Access URI : " + uri.toString()); // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<?> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); String headerValue = req.getHeader(headerName); //LOG.info("header: " + headerName + " value: " + headerValue); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-type")) { request.addHeader(headerName, headerValue + ";charset=\"utf-8\""); } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) { request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; if (!header.getName().equals("Transfer-Encoding")) resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); byte buffer[] = new byte[50]; while (input.read(buffer) != -1) { output.write(buffer); } // int b = input.read(); // while (b != -1) { // output.write(b); // b = input.read(); // } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:org.jclouds.http.apachehc.ApacheHCUtils.java
public HttpUriRequest convertToApacheRequest(HttpRequest request) { HttpUriRequest apacheRequest;//from w ww. j av a 2s . co m if (request.getMethod().equals(HttpMethod.HEAD)) { apacheRequest = new HttpHead(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.GET)) { apacheRequest = new HttpGet(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.DELETE)) { apacheRequest = new HttpDelete(request.getEndpoint()); } else if (request.getMethod().equals(HttpMethod.PUT)) { apacheRequest = new HttpPut(request.getEndpoint()); apacheRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); } else if (request.getMethod().equals(HttpMethod.POST)) { apacheRequest = new HttpPost(request.getEndpoint()); } else { final String method = request.getMethod(); if (request.getPayload() != null) apacheRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; else apacheRequest = new HttpRequestBase() { @Override public String getMethod() { return method; } }; HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint()); } Payload payload = request.getPayload(); // Since we may remove headers, ensure they are added to the apache // request after this block if (apacheRequest instanceof HttpEntityEnclosingRequest) { if (payload != null) { addEntityForContent(HttpEntityEnclosingRequest.class.cast(apacheRequest), payload); } } else { apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0"); } for (Map.Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); // apache automatically tries to add content length header if (!header.equals(HttpHeaders.CONTENT_LENGTH)) apacheRequest.addHeader(header, entry.getValue()); } apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); return apacheRequest; }
From source file:eu.fusepool.p3.proxy.ProxyHandler.java
@Override public void handle(String target, Request baseRequest, final HttpServletRequest inRequest, final HttpServletResponse outResponse) throws IOException, ServletException { final String targetUriString = targetBaseUri + inRequest.getRequestURI(); final String requestUri = getFullRequestUrl(inRequest); //System.out.println(targetUriString); final URI targetUri; try {//w w w . j ava2 s. c o m targetUri = new URI(targetUriString); } catch (URISyntaxException ex) { throw new IOException(ex); } final String method = inRequest.getMethod(); final HttpEntityEnclosingRequestBase outRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; outRequest.setURI(targetUri); String transformerUri = null; if (method.equals("POST")) { if (!"no-transform".equals(inRequest.getHeader("X-Fusepool-Proxy"))) { transformerUri = getTransformerUrl(requestUri); } } final Enumeration<String> headerNames = baseRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (headerName.equalsIgnoreCase("Content-Length") || headerName.equalsIgnoreCase("X-Fusepool-Proxy") || headerName.equalsIgnoreCase("Transfer-Encoding")) { continue; } final Enumeration<String> headerValues = baseRequest.getHeaders(headerName); if (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); outRequest.setHeader(headerName, headerValue); } while (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); outRequest.addHeader(headerName, headerValue); } } final Header[] outRequestHeaders = outRequest.getAllHeaders(); //slow: outRequest.setEntity(new InputStreamEntity(inRequest.getInputStream())); final byte[] inEntityBytes = IOUtils.toByteArray(inRequest.getInputStream()); if (inEntityBytes.length > 0) { outRequest.setEntity(new ByteArrayEntity(inEntityBytes)); } final CloseableHttpResponse inResponse = httpclient.execute(outRequest); try { outResponse.setStatus(inResponse.getStatusLine().getStatusCode()); final Header[] inResponseHeaders = inResponse.getAllHeaders(); final Set<String> setHeaderNames = new HashSet(); for (Header header : inResponseHeaders) { if (setHeaderNames.add(header.getName())) { outResponse.setHeader(header.getName(), header.getValue()); } else { outResponse.addHeader(header.getName(), header.getValue()); } } final HttpEntity entity = inResponse.getEntity(); final ServletOutputStream os = outResponse.getOutputStream(); if (entity != null) { //outResponse.setContentType(target); final InputStream instream = entity.getContent(); try { IOUtils.copy(instream, os); } finally { instream.close(); } } //without flushing this and no or too little byte jetty return 404 os.flush(); } finally { inResponse.close(); } if (transformerUri != null) { Header locationHeader = inResponse.getFirstHeader("Location"); if (locationHeader == null) { log.warn("Response to POST request to LDPC contains no Location header. URI: " + targetUriString); } else { startTransformation(locationHeader.getValue(), requestUri, transformerUri, inEntityBytes, outRequestHeaders); } } }
From source file:com.pmi.restlet.ext.httpclient.internal.HttpMethodCall.java
/** * Constructor./*from w ww .java 2s . co m*/ * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpMethodCall(HttpClientHelper helper, final String method, final String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); this.clientHelper = helper; if (requestUri.startsWith("http")) { if (method.equalsIgnoreCase(Method.GET.getName())) { this.httpRequest = new HttpGet(requestUri); } else if (method.equalsIgnoreCase(Method.POST.getName())) { this.httpRequest = new HttpPost(requestUri); } else if (method.equalsIgnoreCase(Method.PUT.getName())) { this.httpRequest = new HttpPut(requestUri); } else if (method.equalsIgnoreCase(Method.HEAD.getName())) { this.httpRequest = new HttpHead(requestUri); } else if (method.equalsIgnoreCase(Method.DELETE.getName())) { this.httpRequest = new HttpDelete(requestUri); } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) { this.httpRequest = new HttpOptions(requestUri); } else if (method.equalsIgnoreCase(Method.TRACE.getName())) { this.httpRequest = new HttpTrace(requestUri); } else { this.httpRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } @Override public URI getURI() { try { return new URI(requestUri); } catch (URISyntaxException e) { getLogger().log(Level.WARNING, "Invalid URI syntax", e); return null; } } }; } this.responseHeadersAdded = false; setConfidential(this.httpRequest.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName())); } else { throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here"); } }
From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java
/** * The service method from HttpServlet, performs handling of all * HTTP-requests independent of their method. Requests and responses within * the method can be distinguished by belonging to the "frontend" (i.e. the * client connecting to the proxy) or the "backend" (the server being * contacted on behalf of the client)/*from w w w .j a va 2 s. c om*/ * * @param frontendRequest Request coming in from the client * @param frontendResponse Response being returned to the client * @throws ServletException * @throws IOException */ @Override protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse) throws ServletException, IOException { log(LogService.LOG_INFO, "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort() + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " " + frontendRequest.getRequestURI()); if (targetBaseUri == null) { // FIXME return status page return; } //////////////////// Setup backend request final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return frontendRequest.getMethod(); } }; try { backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } //////////////////// Copy headers to backend request final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames(); while (frontendHeaderNames.hasMoreElements()) { final String headerName = frontendHeaderNames.nextElement(); final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); if (!headerName.equalsIgnoreCase("Content-Length")) { backendRequest.setHeader(headerName, headerValue); } } } //////////////////// Copy Entity - if any final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream()); if (inEntityBytes.length > 0) { backendRequest.setEntity(new ByteArrayEntity(inEntityBytes)); } //////////////////// Execute request to backend try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) { frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode()); // Copy back headers final Header[] backendHeaders = backendResponse.getAllHeaders(); final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length); for (Header header : backendHeaders) { if (backendHeaderNames.add(header.getName())) { frontendResponse.setHeader(header.getName(), header.getValue()); } else { frontendResponse.addHeader(header.getName(), header.getValue()); } } final ServletOutputStream outStream = frontendResponse.getOutputStream(); // Copy back entity final HttpEntity entity = backendResponse.getEntity(); if (entity != null) { try (InputStream inStream = entity.getContent()) { IOUtils.copy(inStream, outStream); } } outStream.flush(); } }
From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java
/** * GET/POST/PUT/DELETE ?./* ww w . j a v a2s .c o m*/ * @param method Http * @param url URL * @param body * @param headers ?? * @return DcResponse * @throws DcException DAO */ public DcResponse request(final String method, String url, String body, HashMap<String, String> headers) throws DcException { HttpEntityEnclosingRequestBase req = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; req.setURI(URI.create(url)); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); if (body != null) { HttpEntity httpEntity = null; try { String bodyStr = toUniversalCharacterNames(body); httpEntity = new StringEntity(bodyStr); } catch (UnsupportedEncodingException e) { throw DcException.create("error while request body encoding : " + e.getMessage(), 0); } req.setEntity(httpEntity); } debugHttpRequest(req, body); return this.request(req); }