private static HTTPResponse _invoke(HttpMethod httpMethod, URL url, String username, String password, long timeout, int maxRedirect, String charset, String useragent, ProxyData proxy, Header[] headers, Map<String,String> params, Object body) throws IOException { HttpClient client = new HttpClient(); HostConfiguration config = client.getHostConfiguration(); HttpState state = client.getState(); setHeader(httpMethod,headers); if(CollectionUtil.isEmpty(params))setContentType(httpMethod,charset); setUserAgent(httpMethod,useragent); setTimeout(client,timeout); setParams(httpMethod,params); setCredentials(client,httpMethod,username,password); setProxy(config,state,proxy); if(body!=null && httpMethod instanceof EntityEnclosingMethod)setBody((EntityEnclosingMethod)httpMethod,body); return new HTTPResponse3Impl(execute(client,httpMethod,maxRedirect),url); }
@Override public ClientHttpResponse executeInternal(HttpHeaders headers, byte[] output) throws IOException { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { httpMethod.addRequestHeader(headerName, headerValue); } } if (this.httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) this.httpMethod; RequestEntity requestEntity = new ByteArrayRequestEntity(output); entityEnclosingMethod.setRequestEntity(requestEntity); } this.httpClient.executeMethod(this.httpMethod); return new CommonsClientHttpResponse(this.httpMethod); }
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */ @SuppressWarnings("unchecked") public static void handleMultipartPost( EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // TODO: this function doesn't set any history data try { // just pass back the binary data InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream()); postMethodProxyRequest.setRequestEntity(ire); postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME)); } catch (Exception e) { throw new ServletException(e); } }
private String sendPostData(HttpMethod method) throws IOException { String form; if (useAuthHeader) { form = nonOAuthParams.get(0).getValue(); } else { form = OAuth.formEncode(message.getParameters()); } method.addRequestHeader(HEADER_CONTENT_LENGTH, form.length() + ""); //$NON-NLS-1$ if (method instanceof PostMethod || method instanceof PutMethod) { StringRequestEntity requestEntity = new StringRequestEntity(form); ((EntityEnclosingMethod)method).setRequestEntity(requestEntity); } else { log.error("Logic error, method must be POST or PUT to send body"); //$NON-NLS-1$ } return form; }
private String sendPostData(HttpMethod method) throws IOException { String form; if (useAuthHeader) { form = OAuth.formEncode(nonOAuthParams); } else { form = OAuth.formEncode(message.getParameters()); } method.addRequestHeader(HEADER_CONTENT_TYPE, OAuth.FORM_ENCODED); method.addRequestHeader(HEADER_CONTENT_LENGTH, form.length() + ""); //$NON-NLS-1$ if (method instanceof PostMethod || method instanceof PutMethod) { StringRequestEntity requestEntity = new StringRequestEntity( form, OAuth.FORM_ENCODED, OAuth.ENCODING); ((EntityEnclosingMethod)method).setRequestEntity(requestEntity); } else { log.error("Logic error, method must be POST or PUT to send body"); //$NON-NLS-1$ } return form; }
public HttpMethodAdapter(HttpMethod request, HostConfiguration hostConfiguration) { this.request = request; if (request instanceof EntityEnclosingMethod) { entity = ((EntityEnclosingMethod) request).getRequestEntity(); } hc = hostConfiguration; }
/** * Adds the JSON as request-body the the method and sets the correct * content-type. * @param method EntityEnclosingMethod * @param object JSONObject */ private void populateRequestBody(EntityEnclosingMethod method, JSONObject object) { try { method.setRequestEntity(new StringRequestEntity(object.toJSONString(), MIME_TYPE_JSON, "UTF-8")); } catch (UnsupportedEncodingException error) { // This will never happen! throw new RuntimeException("All hell broke loose, a JVM that doesn't have UTF-8 encoding..."); } }
/** * This function sets the request content. * * @param httpRequest * The HTTP request * @param httpMethodClient * The apache HTTP method */ protected void setRequestContent(HTTPRequest httpRequest,HttpMethodBase httpMethodClient) { //set content if(httpMethodClient instanceof EntityEnclosingMethod) { EntityEnclosingMethod pushMethod=(EntityEnclosingMethod)httpMethodClient; RequestEntity requestEntity=null; ContentType contentType=httpRequest.getContentType(); switch(contentType) { case STRING: requestEntity=this.createStringRequestContent(httpRequest); break; case BINARY: requestEntity=this.createBinaryRequestContent(httpRequest); break; case MULTI_PART: requestEntity=this.createMultiPartRequestContent(httpRequest,httpMethodClient); break; default: throw new FaxException("Unsupported content type: "+contentType); } //set request data if(requestEntity!=null) { pushMethod.setRequestEntity(requestEntity); pushMethod.setContentChunked(false); } } }
/** * Clones a HttpMethod. <br> * <b>Attention:</b> You have to clone a method before it has * been executed, because the URI can change if followRedirects * is set to true. * * @param m the HttpMethod to clone * * @return the cloned HttpMethod, null if the HttpMethod could * not be instantiated * * @throws java.io.IOException if the request body couldn't be read */ public static HttpMethod clone(HttpMethod m) { HttpMethod copy = null; try { copy = m.getClass().newInstance(); } catch (InstantiationException iEx) {} catch (IllegalAccessException iaEx) {} if ( copy == null ) { return null; } copy.setDoAuthentication(m.getDoAuthentication()); copy.setFollowRedirects(m.getFollowRedirects()); copy.setPath( m.getPath() ); copy.setQueryString(m.getQueryString()); Header[] h = m.getRequestHeaders(); int size = (h == null) ? 0 : h.length; for (int i = 0; i < size; i++) { copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue())); } copy.setStrictMode(m.isStrictMode()); if (m instanceof HttpMethodBase) { copyHttpMethodBase((HttpMethodBase)m,(HttpMethodBase)copy); } if (m instanceof EntityEnclosingMethod) { copyEntityEnclosingMethod((EntityEnclosingMethod)m,(EntityEnclosingMethod)copy); } return copy; }
private static void setBody(EntityEnclosingMethod httpMethod, Object body) throws IOException { if(body!=null) try { httpMethod.setRequestEntity(toRequestEntity(body)); } catch (PageException e) { throw ExceptionUtil.toIOException(e); } }
private void recordEntity(HttpMethod httpMethod, Trace trace) { if (httpMethod instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod)httpMethod; final RequestEntity entity = entityEnclosingMethod.getRequestEntity(); if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) { if (entitySampler.isSampling()) { try { String entityValue; String charSet = entityEnclosingMethod.getRequestCharSet(); if (charSet == null || charSet.isEmpty()) { charSet = HttpConstants.DEFAULT_CONTENT_CHARSET; } if (entity instanceof ByteArrayRequestEntity) { entityValue = readByteArray((ByteArrayRequestEntity)entity, charSet); } else if (entity instanceof StringRequestEntity) { entityValue = readString((StringRequestEntity)entity); } else { entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")"; } trace.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue); } catch (Exception e) { logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e); } } } } }
/** * Sets up the given {@link PostMethod} to send the same standard POST data as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod} * @throws IOException */ private void handleStandard(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { try { methodProxyRequest.setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream())); //LOGGER.info("original request content length:" + httpServletRequest.getContentLength()); //LOGGER.info("proxied request content length:" +methodProxyRequest.getRequestEntity().getContentLength()+""); } catch (IOException e) { throw new IOException(e); } }
private void recordEntity(HttpMethod httpMethod, Trace trace) { if (httpMethod instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; final RequestEntity entity = entityEnclosingMethod.getRequestEntity(); if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) { if (entitySampler.isSampling()) { try { String entityValue; String charSet = entityEnclosingMethod.getRequestCharSet(); if (StringUtils.isEmpty(charSet)) { charSet = HttpConstants.DEFAULT_CONTENT_CHARSET; } if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) { entityValue = entityUtilsToString(entity, charSet); } else { entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")"; } final SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue); } catch (Exception e) { logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e); } } } } }
/** * Gets the output stream. * * @return the output stream * @throws EWSHttpException * the eWS http exception */ @Override public OutputStream getOutputStream() throws EWSHttpException { OutputStream os = null; throwIfConnIsNull(); os = new ByteArrayOutputStream(); ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayOSRequestEntity(os)); return os; }
/** * Update entry by posting new representation of entry to server. Note that you should not * attempt to update entries that you get from iterating over a collection they may be "partial" * entries. If you want to update an entry, you must get it via one of the * <code>getEntry()</code> methods in {@link com.rometools.rome.propono.atom.common.Collection} * or {@link com.rometools.rome.propono.atom.common.AtomService}. * * @throws ProponoException If entry is a "partial" entry. */ public void update() throws ProponoException { if (partial) { throw new ProponoException("ERROR: attempt to update partial entry"); } final EntityEnclosingMethod method = new PutMethod(getEditURI()); addAuthentication(method); final StringWriter sw = new StringWriter(); final int code = -1; try { Atom10Generator.serializeEntry(this, sw); method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null)); method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8"); getHttpClient().executeMethod(method); final InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() != 200 && method.getStatusCode() != 201) { throw new ProponoException("ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is)); } } catch (final Exception e) { final String msg = "ERROR: updating entry, HTTP code: " + code; LOG.debug(msg, e); throw new ProponoException(msg, e); } finally { method.releaseConnection(); } }
void addToCollection(final ClientCollection col) throws ProponoException { setCollection(col); final EntityEnclosingMethod method = new PostMethod(getCollection().getHrefResolved()); addAuthentication(method); final StringWriter sw = new StringWriter(); int code = -1; try { Atom10Generator.serializeEntry(this, sw); method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null)); method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8"); getHttpClient().executeMethod(method); final InputStream is = method.getResponseBodyAsStream(); code = method.getStatusCode(); if (code != 200 && code != 201) { throw new ProponoException("ERROR HTTP status=" + code + " : " + Utilities.streamToString(is)); } final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), getCollection().getHrefResolved(), Locale.US); BeanUtils.copyProperties(this, romeEntry); } catch (final Exception e) { final String msg = "ERROR: saving entry, HTTP code: " + code; LOG.debug(msg, e); throw new ProponoException(msg, e); } finally { method.releaseConnection(); } final Header locationHeader = method.getResponseHeader("Location"); if (locationHeader == null) { LOG.warn("WARNING added entry, but no location header returned"); } else if (getEditURI() == null) { final List<Link> links = getOtherLinks(); final Link link = new Link(); link.setHref(locationHeader.getValue()); link.setRel("edit"); links.add(link); setOtherLinks(links); } }
public void testGetNameGetUriAndGetRequestEntity() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream("ASDF".getBytes()); EntityEnclosingMethod method = new GatewayEntityMethod("POST", "http://www.google.com/search", in); assertEquals("POST", method.getName()); assertEquals("http://www.google.com/search", method.getURI().toString()); ByteArrayOutputStream out = new ByteArrayOutputStream(); method.getRequestEntity().writeRequest(out); assertEquals("ASDF", out.toString()); }
private static void copyEntityEnclosingMethod( EntityEnclosingMethod m, EntityEnclosingMethod copy ) throws java.io.IOException { copy.setRequestEntity(m.getRequestEntity()); }
/** * Clones a HttpMethod. <br> * <b>Attention:</b> You have to clone a method before it has * been executed, because the URI can change if followRedirects * is set to true. * * @param m the HttpMethod to clone * * @return the cloned HttpMethod, null if the HttpMethod could * not be instantiated * * @throws java.io.IOException if the request body couldn't be read */ public static HttpMethod clone(HttpMethod m) throws java.io.IOException { HttpMethod copy = null; // copy the HttpMethod try { copy = (HttpMethod) m.getClass().newInstance(); } catch (InstantiationException iEx) { } catch (IllegalAccessException iaEx) { } if ( copy == null ) { return null; } copy.setDoAuthentication(m.getDoAuthentication()); copy.setFollowRedirects(m.getFollowRedirects()); copy.setPath( m.getPath() ); copy.setQueryString(m.getQueryString()); // clone the headers Header[] h = m.getRequestHeaders(); int size = (h == null) ? 0 : h.length; for (int i = 0; i < size; i++) { copy.setRequestHeader( new Header(h[i].getName(), h[i].getValue())); } copy.setStrictMode(m.isStrictMode()); if (m instanceof HttpMethodBase) { copyHttpMethodBase( (HttpMethodBase)m, (HttpMethodBase)copy); } if (m instanceof EntityEnclosingMethod) { copyEntityEnclosingMethod( (EntityEnclosingMethod)m, (EntityEnclosingMethod)copy); } return copy; }
/** * Creates the HttpMethod to use to call the remote server, either its GET or POST. * * @param exchange the exchange * @return the created method as either GET or POST * @throws CamelExchangeException is thrown if error creating RequestEntity */ @SuppressWarnings("deprecation") protected HttpMethod createMethod(Exchange exchange) throws Exception { // creating the url to use takes 2-steps String url = HttpHelper.createURL(exchange, getEndpoint()); URI uri = HttpHelper.createURI(exchange, url, getEndpoint()); // get the url and query string from the uri url = uri.toASCIIString(); String queryString = uri.getRawQuery(); // execute any custom url rewrite String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this); if (rewriteUrl != null) { // update url and query string from the rewritten url url = rewriteUrl; uri = new URI(url); // use raw query to have uri decimal encoded which http client requires queryString = uri.getRawQuery(); } // remove query string as http client does not accept that if (url.indexOf('?') != -1) { url = url.substring(0, url.indexOf('?')); } // create http holder objects for the request RequestEntity requestEntity = createRequestEntity(exchange); String methodName = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null).name(); HttpMethods methodsToUse = HttpMethods.valueOf(methodName); HttpMethod method = methodsToUse.createMethod(url); if (queryString != null) { // need to encode query string queryString = UnsafeUriCharactersEncoder.encode(queryString); method.setQueryString(queryString); } LOG.trace("Using URL: {} with method: {}", url, method); if (methodsToUse.isEntityEnclosing()) { ((EntityEnclosingMethod) method).setRequestEntity(requestEntity); if (requestEntity != null && requestEntity.getContentType() == null) { LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange); } } // there must be a host on the method if (method.getHostConfiguration().getHost() == null) { throw new IllegalArgumentException("Invalid uri: " + url + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint()); } return method; }
private static void copyEntityEnclosingMethod(EntityEnclosingMethod m, EntityEnclosingMethod copy ) { copy.setRequestEntity(m.getRequestEntity()); }
/** * Performs an HTTP request * * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine representing the client request to be proxied * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a proxied response to the client */ public void doMethod(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { ProxyMethodConfig methodConfig = proxyHelper.prepareProxyMethod( httpServletRequest, httpServletResponse, this); if (methodConfig != null) { // ////////////////////////////// // Create a request // ////////////////////////////// HttpMethod methodProxyRequest = methodConfig.getMethod(); // ////////////////////////////// // Forward the request headers // ////////////////////////////// final ProxyInfo proxyInfo = setProxyRequestHeaders(methodConfig.getUrl(), httpServletRequest, methodProxyRequest); // ////////////////////////////////////////////////// // Check if this is a mulitpart (file upload) PUT | POST // ////////////////////////////////////////////////// if(methodProxyRequest instanceof EntityEnclosingMethod){ if (ServletFileUpload.isMultipartContent(httpServletRequest)) { this.handleMultipart((EntityEnclosingMethod)methodProxyRequest, httpServletRequest); } else { this.handleStandard((EntityEnclosingMethod)methodProxyRequest, httpServletRequest); } } // ////////////////////////////// // Execute the proxy request // ////////////////////////////// this.executeProxyRequest(methodProxyRequest, httpServletRequest, httpServletResponse, methodConfig.getUser(), methodConfig.getPassword(), proxyInfo); } }
private void addHeaderToRequest(Map<String, String> header, EntityEnclosingMethod request) { for(Map.Entry<String,String> entry : header.entrySet()) { request.addRequestHeader(entry.getKey(), entry.getValue()); } }
/** Package access, to be called by DefaultClientCollection */ @Override void addToCollection(final ClientCollection col) throws ProponoException { setCollection(col); final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved()); getCollection().addAuthentication(method); try { final Content c = getContents().get(0); if (inputStream != null) { method.setRequestEntity(new InputStreamRequestEntity(inputStream)); } else { method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes()))); } method.setRequestHeader("Content-type", c.getType()); method.setRequestHeader("Title", getTitle()); method.setRequestHeader("Slug", getSlug()); getCollection().getHttpClient().executeMethod(method); if (inputStream != null) { inputStream.close(); } final InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() == 200 || method.getStatusCode() == 201) { final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), col.getHrefResolved(), Locale.US); BeanUtils.copyProperties(this, romeEntry); } else { throw new ProponoException("ERROR HTTP status-code=" + method.getStatusCode() + " status-line: " + method.getStatusLine()); } } catch (final IOException ie) { throw new ProponoException("ERROR: saving media entry", ie); } catch (final JDOMException je) { throw new ProponoException("ERROR: saving media entry", je); } catch (final FeedException fe) { throw new ProponoException("ERROR: saving media entry", fe); } catch (final IllegalAccessException ae) { throw new ProponoException("ERROR: saving media entry", ae); } catch (final InvocationTargetException te) { throw new ProponoException("ERROR: saving media entry", te); } final Header locationHeader = method.getResponseHeader("Location"); if (locationHeader == null) { LOG.warn("WARNING added entry, but no location header returned"); } else if (getEditURI() == null) { final List<Link> links = getOtherLinks(); final Link link = new Link(); link.setHref(locationHeader.getValue()); link.setRel("edit"); links.add(link); setOtherLinks(links); } }
public void testService_POST() throws Exception { expect(request.getMethod()).andStubReturn("POST"); expect(request.getRequestURI()).andStubReturn("/relativeUri"); final ByteArrayInputStream input = new ByteArrayInputStream("ASDF".getBytes()); ServletInputStream in = new ServletInputStream() { @Override public int read() throws IOException { return input.read(); } }; expect(request.getInputStream()).andStubReturn(in); expect(request.getHeaderNames()).andStubReturn( Iterators.asEnumeration(ImmutableList.of("Host").iterator())); expect(request.getHeaders("Host")).andStubReturn( Iterators.asEnumeration(ImmutableList.of("jstd:80").iterator())); expect(request.getQueryString()).andStubReturn("id=123"); // TODO(rdionne): Feed fake response values into the captured HttpMethod and assert they are // properly converted to equivalent HttpServletResponse fields. Capture<HttpMethodBase> methodCapture = new Capture<HttpMethodBase>(); expect(client.executeMethod(EasyMock.capture(methodCapture))).andStubReturn(200); /* expect */ response.setStatus(200); expect(request.getHeaders("Pragma")).andStubReturn( Iterators.asEnumeration(Iterators.emptyIterator())); final ByteArrayOutputStream output = new ByteArrayOutputStream(); ServletOutputStream out = new ServletOutputStream() { @Override public void write(int b) throws IOException { output.write(b); } }; expect(response.getOutputStream()).andStubReturn(out); control.replay(); gateway.handleIt(); ByteArrayOutputStream requestBody = new ByteArrayOutputStream(); ((EntityEnclosingMethod) methodCapture.getValue()).getRequestEntity().writeRequest(requestBody); assertEquals("POST", methodCapture.getValue().getName()); assertEquals("http://hostname/relativeUri?id=123", methodCapture.getValue().getURI().toString()); assertEquals("hostname:80", methodCapture.getValue().getRequestHeader("Host").getValue()); assertEquals("id=123", methodCapture.getValue().getQueryString()); assertEquals("ASDF", requestBody.toString()); assertEquals("", output.toString()); }